For loop error (SOLVED)

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.

for i in 1,#self.path_nodes do

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.

3 Likes

It’s valid syntax when using a table

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
1 Like

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 :stuck_out_tongue: EDIT: Ah yeah as Pkeod says, this is valid when accessing a table. Why the idiosyncrasy here?

1 Like

Lua doesn’t require a space. You were using in instead of an = sign.

2 Likes

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
5 Likes

I count eight superfluous spaces in that line!

4 Likes

Ah thanks, I need to stop drinking and coding so frequently :blush:

3 Likes