如何在Lua中引用表中的int值?这甚至可能吗?

时间:2013-09-15 22:13:17

标签: reference lua

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

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

如果我运行它,值num只会被复制,但我需要一个引用。 我正在和lualö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") -- is equal to 
entity.components.StringComponent -- StringComponent is just 
                                  -- a component added to the entity 

StringComponent是一个包含3个字段的简单类。

StringComponent = class("StringComponent")

function StringComponent:__init(font, string, values) 
    self.font = font
    self.string = string
    self.values = values
end

3 个答案:

答案 0 :(得分:2)

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

x = 5
table = {}

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

print(table["key"]()) -- Will print 5
x = 10
print(table["key"]()) -- Will print 10

答案 1 :(得分:2)

如果没有更多级别的重定向,则无法执行此操作,因为您无法引用数值。您可以在表中存储所需的值并修改该表中的第一个元素:

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

答案 2 :(得分:0)

我找到了解决当前问题的方法。我想引用的每个int都以某种方式表示另一个表的子节点。因此,例如,如果您想引用table.inttable2.int2,我会在StringComponent的构造函数中将{{table, "int"}, {table2, "int2"}}传递给values。 现在,您可以使用

创建包含更新值的表
local val = {}
for k, v in pairs(str.values) do
    table.insert(val, v[1][v[2]])
end

现在我可以使用

格式化字符串
string.format(str.string, unpack(val))

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