I want to refer to an integer, but the reference should be inside a table. The goal is an automatic string formatting function, which is updating the values every frame.
>> num = 5
>> table = {}
>> table[1] = num
>> num = 10
>> print(table[1])
>> 5
If i run this the value num is only getting copied, but i need a reference instead. I am writing a game with the lua löve2D library at the moment. Here is an excerpt of my code:
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 is a table that should contain the references to the wanted values. Those values are not necessarily global.
entity:getComponent("StringComponent") -- is equal to
entity.components.StringComponent -- StringComponent is just
-- a component added to the entity
StringComponent is a simple class with 3 fields.
StringComponent = class("StringComponent")
function StringComponent:__init(font, string, values)
self.font = font
self.string = string
self.values = values
end
entity:getComponentthe function responsible for setting upstr.values's table?str.valuesso it triggers a__indexand have the metamethod build up the table of values to return on-the-fly. But you still need to know where to get those values from -- probably do this via an upvalue like Colonel showed. I can give a more concrete example if you show howstr.valuesis being setup.