23. Lua 队列 的基本操作 (集合 无序组 包)

本文介绍了Lua中的table原生操作效率问题,重点展示了如何通过自定义List类实现队列功能,以及如何管理和避免使用保留字,包括Set数据结构和insert/remove函数的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • Lua 原有的对 table 的插入和删除 , 但效率较低
    -- table.insert() 在数组中插入元素
    -- table.remove() 在数组中删除元素
    
  • Lua 中队列 的基本操作实现
    List = {}
    -- 返回队列的队首和 队尾
    function List.new()
      return { first = 0 , last = -1 }
    end
    
    -- 在队首插入新的元素
    function List.pushfirst( liast , value )
      local first = list.first - 1
      list.first = first
    end
    
    -- 在队尾插入新的元素
    function List.pushlast( list , value )
      local last = list.last + 1
      list.last = last
      list.[last] = value
    end
    
    -- 在队首删除元素
    function List.popfirst( list )
      local first = list.first
      if  first > list.last then
      	error("list  is empty")
      end
      local value = list[first]
      list[first] = nil   -- 为了允许垃圾收集
      list.first = first + 1
      return value
    end
    
    -- 在队尾删除元素
    function List.poplast( list )
      local last = list.last
      if list.first > last then
      	error("list is empty")
      end
      local value = list[last]
      list[last] = nil -- 为了允许垃圾收集
      list.last = last - 1
      return value
    end
    
  • 集合与无序组
    reserved = { "while" = true , ["end"] = true , ["function"} = true , ["lcoal"] = true }
    --[[
    for w in allwords()
      if not reserved[w] then
      	<对 w 做处理的代码> -- w 不是一个保留字
      end
    end
    --]]
    -- 初始化 保留字集合
    function Set( list )
      local set = {}
      for _ , l ipairs( list ) do
      	set[l] = true
      end
      return set
    end
    
    reserved = Set{ "while" , "end" , "function" , "lcoal" }
    
  •  function insert( bag , element )
      bag[element] = (bag[element] or 0 ) + 1
    end
    
    function remove( bag , element )
      local count = bag[element]
      bag[element] = ( count and count > 1 ) and count - 1 or nil
    
    end
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值