[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: why doesnt a[1] = 1 work?
- From: "Markus Heukelom" <Markus.Heukelom@...>
- Date: Wed, 23 May 2007 13:33:34 +0200
> a = "" and a = "lua" are not declarations, they are assignments.
> You're assigning string values to the variable 'a', which may
> or may not have had a value assigned to it previously.
>
> a = {} is assigning a table value to the variable 'a', which
> may or may not have had a value assigned to it previously.
>
> If you try to use 'a' in an expression before a value has
> been assigned to it, you will likely get an error. For
> instance, if you say
> io.write(a) before assigning a value to 'a', you'll get an
> error because io.write expects a value and you passed it nil.
> Similarly, if you try to index 'a' (i.e. io.write(a[1]) or
> a[1] = 1) before assigning a table value to it, you'll get en
> error because you cannot index nil.
Thanks, but it doesn't answer may question completely though. I'll try to
put it more specifically:
a = "lua"
a[1]=1 -- error: indexing a string value
a = nil
a[1]=1 -- error: indexing a nil value
Yes, I understand this. I can't index anything but a table.
But you could also read this as: assign a the table value {1=1}, if a is not
of type table. (Ofcourse, if a is a table the index would be
created/overwritten).
Because lua is loosely typed, it feels a bit strange to 'declare' (between
quotes!) a table by first assigning it a (empty) table and then assign new
(key, value)-tuples to it.
As an example:
a = {}
for i=1,10
a[i]=math.random(10)
end
I like the conciseness of lua, so I'd be glad to get rid of the a = {},
which just feels a little redundant here. Ofcourse, a = nil; print(a[1])
would still not compile.
I understand that this is maybe more of a feature request than a question
though...
Markus