• Subject: Re: Arithmetic on table fields passed as function argument
• From: Andrew Starks <andrew.starks@...>
• Date: Sat, 14 Sep 2013 20:41:39 -0500

On Saturday, September 14, 2013, Jayanth Acharya wrote:
Admittedly, I have adopted a lazy and somewhat (perhaps) unconventional approach to learning Lua, i.e. by trying out what I've learnt so far supplanted by a bit of intuition.

Here's one snippet that stumped me. Lua didn't like me doing arithmetic on table fields, but from what I've read so far, I couldn't figure out an obvious reason.

[code]
t = {}
t.distance = 40
t.time = 2.5

for k,v in pairs(t) do print(k,v) end

function speed(tab) return tab.distance/tab.time end

t.speed = speed{t}

for k,v in pairs(t) do print(k,v) end
[/code]

Lua barfs out this output:-

[output]
time    2.5
distance    40
lua: 8.lua:7: attempt to perform arithmetic on field 'distance' (a nil value)
stack traceback:
8.lua:7: in function 'speed'
8.lua:9: in main chunk
[C]: ?
[/output]

Why so ?

Your call to speed is the problem:

speed{t}

Wraps t in a table so that:

Speed gets tab[1].distance has what you want.

Change the call to speed(t)

The {} variant is used when you want to make named arguments.

speed{distance= 40, time=2.5}

Would also work.

Now I'll try not to send this email 3 times.

-Andrew