【问题标题】:Lua overloads the operator to create a fake arrayLua 重载操作符来创建一个假数组
【发布时间】:2023-01-12 17:12:34
【问题描述】:

我想创建一个 0 内存的 lua 数组,当我在上面使用像 # [] 这样的运算符时,它实际上跳转到我的自定义函数

关于如何做到这一点的任何想法?

我希望使用这个假数组的用户不会认为它是假的,它在访问速度方面比普通数组差,但内存性能更好

【问题讨论】:

  • 只需为您的假数组实现 __len__pairs__index 元方法。
  • @EgorSkriptunoff 非常感谢
  • 请不要将新用户投票给遗忘。你是问题所在。

标签: lua lua-table


【解决方案1】:

Lua 实现了一种叫做元方法的东西(documentation

元方法是存在于表之后并触发某些操作的函数,例如索引数组、读取丢失的索引、收集数组的长度,甚至是数学运算,例如 + - * /

-- Start by creating your array, and another for demonstration purposes
local object = {}
local demo = {1, 2, 3, 4}

-- Create a your metamethods contained in a table
local metamethods = {
    __index = function(self, index) return demo[index] end;
    __newindex = function(self, index, value) demo[index] = value end;
}

-- Lets print out what is in the object table for demonstration
print(object[1]) -- nil
print(object[2]) -- nil
print(object[3]) -- nil
print(object[4]) -- nil

-- Use the setmetatable(table a, table b) function to set the metamethods
-- stored in 'b' to 'a'
setmetatable(object, metamethods);

-- Lets print out what is in the object table for demonstration
print(object[1]) -- 1
print(object[2]) -- 2
print(object[3]) -- 3
print(object[4]) -- 4

为什么上面的代码有效?当使用索引__indexmetamethods.__index)设置元表时,如果附加表的(object)键是nil,那么它将调用指定的函数。在这种情况下,它返回演示的表,索引直接传递给它。就好像:当你做object[1]时,你实际上做的是demo[1],当然是在元方法的帮助下。

setmetatable() 的一个很酷且快速的用法是它返回您作为第一个参数(表)传递的值。如果您将 nil 传递给第一个参数,它将为您提供一个新表。

local object1 = setmetatable({}, { __index = function(self, i) return 1 end })
local object2 = setmetatable(nil, { __index = function(self, i) return 2 end })

print(object1["a"])
print(object2[321])

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    相关资源
    最近更新 更多