[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: String parameters when calling C from Lua
- From: Mike Pall <mikelu-0605@...>
- Date: Fri, 19 May 2006 12:52:09 +0200
Hi,
Daniel Collins wrote:
> When calling a C function from lua with a string argument, is that
> string copied onto the stack that the C function gets? Or does the stack
> contain a pointer to the original string?
No. Yes.
The Lua stack is just an array of TValue's. In your case this
boils down to an int (for the type) and a pointer (to the string
plus a header) for each stack slot.
Lua strings are immutable, shared and pre-hashed. Constant
strings (i.e. t.key or t["key"]) are hashed once when the script
is loaded.
A string lookup is then just a couple instructions in the fast
path. See luaH_getstr() and realize that the hashstr() macro is
just a bitmask operation and an array lookup. Hashing is done
once when a Lua string is created (see luaS_newlstr()), not when
it is used as a key.
A corollary of this is that you should avoid converting C strings
to Lua strings over and over again. lua_push[l]string() has to
rehash it and lookup it up in the shared string table. Try to
keep repeatedly used Lua strings in upvalues or arrays. Or,
better yet, in Lua code.
> I am wondering about the most
> efficient way to implement localisable string tables. I can see two ways
> of doing this but I want to use the most efficient implementation. The
> two methods can be boiled down to:
>
> Method One:
> -- StringTable.lua
> stringtable =
> {
> mainmenu = "main",
> quit = "quit",
> yes = "yes"
> }
>
> -- SomeMenu.lua
> require "StringTable"
> callSomeCFunction(stringtable.yes)
One hash table lookup.
> Method Two:
> -- StringTable.lua
> LoadStringData("stringdata.bin") -- loads the actual strings into a C
> array
>
> stringtable =
> {
> mainmenu = 1,
> quit = 2,
> yes = 3
> }
>
> -- SomeMenu.lua
> require "StringTable"
> callSomeCFunction(stringtable.yes) -- integer argument indexes the C
> array loaded earlier
One hash table lookup and on the C side a double->int conversion
and one array lookup. Slower.
General rule: Lua's hash tables are very fast. Particularly when
used with constant strings. Use them if you can.
Trying to avoid a hash lookup does not pay off. And a workaround
may be slower due to other issues (as seen above).
Bye,
Mike