lua-users home
lua-l archive

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

A. Even though you said "they only receive the lua_State* parameter", I'm
assuming you know all about the Lua stack and how to get the Lua parameters
and return values to Lua.

B. The typical way of exporting objects (i.e. an instantiation of a class)
to Lua is as userdata's.  Userdata's can have metatables, so you can put the
__index and __newindex methods to good use.  For instance, you can set the
__index member of the userdata's metatable to a Lua table containing the
exported versions of your static C++ functions.

C. The common syntax for calling "methods" in Lua is Object:Method(args)
which turns into Object.Method(Object, args), which means that the Object
(in this discussion a userdata) is passed as the first argument to the

D. So, if you write your C++ static member functions to pull a userdata from
the first parameter on the stack, then you can extract a pointer to a C++
object from that userdata (either by storing the pointer value in the
userdata space or storing the entire object in the userdata space), and then
you can use that to call a NON-static member function.

-----Original Message-----
[]On Behalf Of Tim Conkling
Sent: Tuesday, October 21, 2003 1:04 PM
To: lua-l
Subject: Lua C Functions in C++ class

I have a C++ class that exports some functions to a Lua environment.
These functions are, of course, static, but they need to access member
functions/variables of the class. The only way to do this (that I can
think of) is to make those class members static as well, because
there's no way to associate any sort of user data with the exported
functions -- they only receive the lua_State* parameter, so I can't
tell them which class they belong to when they're called. This wouldn't
be such a problem, except that it's possible I might want multiple
instances of this class at once, and clearly if they're both
manipulating the same static members, there'll be problems, since these
members really shouldn't be static.

I can't think of a great way to solve this problem that doesn't involve
jumping through hoops every time a function of the class gets called.
Is there a design pattern I'm missing here? What do other people do in
this situation?