lua-users home
lua-l archive

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


The section "Saving Tables without Cycles" in the "Programming
in Lua" book notes of table keys: "We can improve this result
by testing [of a key] wether it needs the square brackets", but
leaves that as an excercise to the reader.

This reader has not found an efficient means of testing wether
a string is an unreserved identifier. Something like the following
works:
if string.find(mystring,"[^_%w]") then
    error("only underscores and alphanumerical characters allowed.")
end
if (not loadstring("return {"..mystring.."=42}")) then
    error("leading digits and lua reserved names are prohibited.")
end    
but this requires loading a chunk.

Maintaining a list of reserved names would be more efficient,
but that is prone to breakage for later lua versions. Since all
the requisite information and checks are already part of lua,
it'd be nice if these were exposed as a "string.isidentifier"
library function or similar.

On a related note, it is possible to markedly clean up serialized
data by writing array-like tables without keys. The problem is
to determine, on serialization, wether a table is array-like. The
best solution I've found is:
function arraylike(tab)
    local keys=0
    for k,v in pairs(tab) do keys=keys+1 end
    return table.getn(tab)==keys
end
Is there a more efficient way of doing so in lua? If not, I think
lua contains internal optimizations for array-like tables and
thus is likely aware of their array likeness. A "table.isarraylike"
library function would be handy.

Lastly, serialization of infinite numbers and numbers that are
not a number requires special handling for which there are
no good provisions.

Albert-Jan