如何在Lua中引用表中的整数值?这是否可能?

我想引用一个整数,但引用应该在表中。目标是一个自动字符串格式化函数,它会每帧更新值。

>> num = 5
>> table = {}
>> table[1] = num
>> num = 10
>> print(table[1])
>> 5

如果我运行这个,num值只是被复制,但我需要一个引用。

我现在正在使用lua löve2D库编写一款游戏。这是我的代码节选:

function StringDrawSystem:draw()
    for index, entity in pairs(self.targets) do
        local str = entity:getComponent("StringComponent")
        love.graphics.setFont(str.font)
        local position = entity:getComponent("PositionComponent")
        love.graphics.print(string.format(str.string, unpack(str.values)), position.x, position.y)
    end
end

str.values是一个表,应该包含对所需值的引用。这些值不一定是全局的。

entity:getComponent("StringComponent") -- 等同于
entity.components.StringComponent -- StringComponent只是
                                  -- 添加到实体的组件之一

StringComponent是一个简单的类,有3个字段。

StringComponent = class("StringComponent")

function StringComponent:__init(font, string, values)
    self.font = font
    self.string = string
    self.values = values
end
点赞
用户646619
用户646619

你不能直接这样做,但你可以提供一个闭包,在需要字符串值时调用它,像这样:

x = 5
table = {}

table ["key"] = function () return x end

print (table ["key"] ()) - 将打印 5
x = 10
print (table ["key"] ()) - 将打印 10
2013-09-15 22:20:23
用户1442917
用户1442917

你不能直接引用数字值,必须再增加一层引用。你可以将需要的值存储在一个表格中,并修改该表格中的第一个元素:

num = {}
num[1] = 5
table = {}
table[1] = num
num[1] = 10
print(table[1][1])
-- 10
2013-09-16 01:39:51
用户2782115
用户2782115

我找到了解决方案来解决当前的问题。我想参考的每个 int 都是另一张表的某种形式的子级。因此,例如,如果要引用 table.inttable2.int2,则将 { {table,“int”},{table2,“int2”} } 传递给StringComponent构造函数中的values。 现在,您可以使用以下内容创建具有更新值的表:

本地值= {}
对于k,v在pairs(str.values)中做
    表。insert(val,v [1] [v [2]])
结束

现在,我能够格式化字符串:

string.format(str.string, unpack(val))

如果您有更好的解决方案,请随意发布,以便我可以优化我的代码。

2013-09-17 13:10:46