lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

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.

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

Lua barfs out this 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]: ?

Why so ?

Your call to speed is the problem:


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.