Functions within tables (LUA-Question)
Posted: Sat Jul 06, 2019 2:51 pm
Hi everybody,
this is probably more a LUA then a factorio question, but I hope I'm still in the right place here... I want to store a function in a table and access other values in the table from within that function.
See this example:
In the on_entity_build event I create a table with the entity and some other values and store it in a global table:
Then later I can access and use the other values for example like this :
So far no problem, but I would like to bring this one step further and store a sum function within the table, so that i can just do: local sum = h.sum().
How does this work?
I was assuming something like this, but apparently you can't access value_a and value_b like this:
this is probably more a LUA then a factorio question, but I hope I'm still in the right place here... I want to store a function in a table and access other values in the table from within that function.
See this example:
In the on_entity_build event I create a table with the entity and some other values and store it in a global table:
Code: Select all
local h = {
entity = event.created_entity,
value_a = 1,
value_b = 2
}
table.insert(global.mytable,h)
Code: Select all
for _,h in pairs(global.mytable) do
local sum = h.value_a + h.value_b
end
How does this work?
I was assuming something like this, but apparently you can't access value_a and value_b like this:
Code: Select all
local h = {
entity = event.created_entity,
value_a = 1,
value_b = 2,
sum = function()
return value_a + value_b
end
}
table.insert(global.mytable,h)