I’m running into a very strange error w/ using a for loop.
I have the following code:
local function construct_node_path(self)
self.segment_dists = {}
for i in 1,#self.path_nodes do
local j = i+1
if j > #self.path_nodes then
j = 1
end
-- relative contribution of the segment
local distsqr = vmath.length_sqr(self.path_nodes[i].pos - self.path_nodes[j].pos)
table.insert(self.segment_dists, distsqr)
end
end
which creates the following error:
ERROR:SCRIPT: /game_objects/dungeon/pusher_block.script:37: attempt to call a number value
stack traceback:
/game_objects/dungeon/pusher_block.script:37: in function ‘construct_node_path’
/game_objects/dungeon/pusher_block.script:54: in function </game_objects/dungeon/pusher_block.script:48>
However if I refactor it to
local function construct_node_path(self)
self.segment_dists = {}
local i = 1
while i <= #self.path_nodes do
local j = i+1
if j > #self.path_nodes then
j = 1
end
-- relative contribution of the segment
local distsqr = vmath.length_sqr(self.path_nodes[i].pos - self.path_nodes[j].pos)
table.insert(self.segment_dists, distsqr)
i = i + 1
end
end
there is no error.
The only search result I can find mentioning this is a closed topic on the LuaJIT github page:
Anyone seen this or know what’s going on? This seems like a concern w/ LuaJIT but it could be something else.
Maybe I’m ignorant of some fancy way to write for loops, but to my knowledge this is not Lua. Write a for loop like so:
for i = 1, #self.path_nodes do
It gives you the error attempt to call a number value because using the in keyword in a for loop implies that you’re looping through some table using a function like ipairs().
For example: for index, value in ipairs(my_table) do.
Ah that fixes it. Strange, why does the compiler require a space after the comma in a for loop? Isn’t a comma sufficient to break up the syntax? I guess this is just some LUA weirdness I’m not used to EDIT: Ah yeah as Pkeod says, this is valid when accessing a table. Why the idiosyncrasy here?
It’s the =/ in not the space. Lua could be minified to have very little white space and it would still work. For example the line above could be very ugly but runable as.
local mystuff = {1,2,3} for i=1, #mystuff do print(mystuff[i]) end for k,v in ipairs(mystuff) do print(mystuff[k], v) end