tags:

views:

193

answers:

4

I know of: http://lua-users.org/wiki/SimpleLuaApiExample

It shows me how to build up a table (key, value) pair entry by entry.

Suppose instead, I want to build a gigantic table (say something a 1000 entry table, where both key & value are strings), is there a fast way to do this in lua (rather than 4 func calls per entry:

push
key
value
rawset

Thanks!

A: 

Unfortunately, for associative tables (string keys, non-consecutive-integer keys), no, there is not.

For array-type tables (where the regular 1...N integer indexing is being used), there are some performance-optimized functions, lua_rawgeti and lua_rawseti: http://www.lua.org/pil/27.1.html

Amber
+1  A: 

For string keys, you can use lua_setfield.

lhf
+1  A: 

What you have written is the fast way to solve this problem. Lua tables are brilliantly engineered, and fast enough that there is no need for some kind of bogus "hint" to say "I expect this table to grow to contain 1000 elements."

Norman Ramsey
A: 

You can use createtable to create a table that already has the required number of slots. However, after that, there is no way to do it faster other than

for(int i = 0; i < 1000; i++) {
    lua_push... // key
    lua_push... // value
    lua_rawset(L, tableindex);
}
DeadMG
you don't need to duplicate the table on the stack? rawset doens't consume the table?
anon
No. Rawset only consumes the key and value. Else, how could you ever set more than one k, v pair into one table?
DeadMG