[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Arithmetic on table fields passed as function argument
- From: Choonster TheMage <choonster.2010@...>
- Date: Sun, 15 Sep 2013 11:40:39 +1000
On 15 September 2013 11:33, Jayanth Acharya <jayachar88@gmail.com> 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}
On this line, you're calling the `speed` function with a new table
that has the existing table `t` at index 1. This new table doesn't
have any values for the distance/time fields, so both indexing
operations return nil; causing the division to fail.
If you want to pass `t` as the first argument to `speed`, use
parentheses instead of curly braces. i.e. `speed{t}` becomes
`speed(t)`. Why so ?