Nukesor
Nukesor

Reputation: 118

How to refer to an int value inside a table in Lua? Is that even possible?

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

Upvotes: 3

Views: 608

Answers (3)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26609

You can't do this directly, but you can instead provide a closure to call when you need the string value, like this:

x = 5
table = {}

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

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

Upvotes: 2

Nukesor
Nukesor

Reputation: 118

I found a solution for my current problem. Every int i want to reference is in some kind of way a child of another table. So, for example, if you want to refer to table.int and table2.int2 i pass {{table, "int"}, {table2, "int2"}} to values in the StringComponent's constructor. Now you are able to create a table with the updated values by using

local val = {}
for k, v in pairs(str.values) do
    table.insert(val, v[1][v[2]])
end

Now i am able to format the string with

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

If you have a better solution, feel free to post it, so i can optimize my code.

Upvotes: 0

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

You can't do it without one more level of redirection, as you can't have references to numerics values. You can store the value you need in a table and modify the first element in that table:

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

Upvotes: 2

Related Questions