lua-users home
lua-l archive

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


On Thursday 25 January 2007 11:22 am, Jimmie Houchin wrote:
> Okay, I learned that '000' is not a valid name in Lua.
> But for whatever reason it is accepted successfully as a table index.
> I don't if that is something I can depend on or not.

you're mixing two different concepts used at very different parts of the 
language: names and values.

a value can be a lot of things: a number, a string, nil, a table, a function, 
true, false... (anything else?)

you can use as table keys any value except nil and NaN, as Rici explained.

a Name, OTOH, is a parser concept.  its a small part of your source code, you 
can use names to identify variables or special words.  since the parser can 
pick a name from the source code, and any name can be expressed as a string 
value, there's a nice notation to use tables as 'records', or 'objects'.

simply put:

table.name  ==== table["name"]

this is called "syntactic sugar", because it makes code more attractive, but 
don't add any nutritional value.  the compiled code is exactly the same on 
both cases.

but, since there's no quoting around the name in the left form, you can't 
expect it to work with keys that are somewhat 'ugly'

some examples:

table["two words"]			-- ok
table.two words				-- wrong!!

table["123"]				-- ok
table.123					-- wrong!!

table["this-that"]			-- ok
table.this-that				-- wrong!!

table["you!@#$@#$#%"]	-- ok
table.you!@#$@#$#%		-- wrong!!

table["_"]					-- ok
table._					-- wrong!

also, since the dot notation is sugar for _string_ values, you have to watch 
out when the key isn't a string:

table[true]				-- key is the boolean true value 
table.true					-- key is the string "true"

table[123]					-- key is a number
table["123"]				-- key is a string

table[var]					-- key is the value of the variable
table.var					-- key is the string "var"


in short: you are really free to use almost anything as a table key, the 
limitation is only for the "dot notation" syntactic sugar.

as David noted, you should only use dot notation for constant keys, typically 
record fields, object members and such.  for anything else (especially when 
the key is variable, and user entered!) use the 'real' form: []

-- 
Javier

Attachment: pgpI5BRPXQcDp.pgp
Description: PGP signature