官术网_书友最值得收藏!

Making a stack

Stack data structure can be defined in the Lua language as a closure that always returns a new table. This table contains two functions defined by keys, push and pop. Both operations run in constant time.

Getting ready

Code from this recipe will be probably used more than once in your project so that it can be moved into the Lua module file with similar algorithms. The module file can use the following structure:

-- algoritms.lua

-- Placeholder for a stack data structure code 

return {
  stack = stack,
}

This module structure can be used with algorithms from other recipes as well to keep everything organized.

How to do it…

The following code contains a local definition of the stack function. You can remove the local statement to make this function global or include it as part of the module:

local function stack()
  local out = {}
  out.push = function(item)
    out[#out+1] = item
  end
  out.pop = function()
    if #out>0 then
      return table.remove(out, #out)
    end
  end
  out.iterator = function()
    return function()
      return out.pop()
    end
  end
  return out
end

This stack data structure can be used in the following way:

local s1 = stack()
-- Place a few elements into stack
for _, element in ipairs {'Lorem','ipsum','dolor','sit','amet'} do
  s1.push(element)
end

-- iterator function can be used to pop and process all elements
for element in s1.iterator() do
     print(element)
end

How it works…

Calling the stack function will create a new empty table with three functions. Push and pop functions use the property of the length operator that returns the integer index of the last element. The iterator function returns a closure that can be used in a for loop to pop all the elements. The out table contains integer indices and no holes (without empty elements). Both the functions are excluded from the total length of the out table.

After you call the push function, the element is appended at the end of the out table. The Pop function removes the last element and returns the removed element.

主站蜘蛛池模板: 乳山市| 长沙市| 大兴区| 临沭县| 金湖县| 缙云县| 乌海市| 凉山| 寻甸| 西乡县| 福泉市| 新乡市| 广州市| 黎川县| 安西县| 江都市| 盐亭县| 鹰潭市| 玛曲县| 潜山县| 宜君县| 怀远县| 民乐县| 宁城县| 宁陵县| 揭东县| 策勒县| 阳江市| 鹤庆县| 嘉峪关市| 隆化县| 沈阳市| 兴国县| 凤台县| 常州市| 满洲里市| 辽阳市| 法库县| 海兴县| 伊吾县| 拜城县|