lua-users home
lua-l archive

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


Hello. I’m fairly new to lua but have been lurking on this list for some time now. I have a simple (ish) question in a simple context...

I have a lua table whose metatable’s __index is a c function, to implement a simple binding to some c-side properties of the object that the table represents.

The c function basically first looks to see if it can satisfy the indexing operation on the ‘c side’, before emulating the usual lua behaviour. So far so good. The code of the c function effectively becomes a ‘switch’ on the key value passed in. Thus I would like to be able to rapidly compare the key against a number of known strings.

I was wondering, could I just directly compare the key string’s *pointer* (by burrowing inside the VM’s string data structure) with some string pointer stored away at initialization time? (I would make sure that this original string was never gc’ed, of course)

I think this is possible - as a by-product of that fact that equal strings in lua only get allocated once. It certainly seems to be the way the VM works and was the motivation for lua's string system. but is it evil and bad and awful to rely on that fact? And is this a bad use of this property? I suppose it is evil, but it would be faster than constructing the string in the __index, pushing it on the stack each time and then comparing ‘properly’. Seems a lot of overhead that way.

Or am I being dumb and there is another way to go, which is fast and has low overhead but requires less ugliness?

Of course stepping back, the other option in implementing this, is to rely less on my c __index function, and instead let lua do the matching of keys – add a heavy user data for each key, with their own metatables, and let lua’s hashed table lookup code take the strain.

Sorry if this is a really dumb question, flames or comments are more than welcome ☺ Thanks in advance for your time, Cheers Alex

Ps Thanks also to all the lua authors & community - I enjoy reading this list very much and it seems from my limited experience with lua that it is a great piece of work.