lua-users home
lua-l archive

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


I am writing a game that uses Lua to expose its object model to adventurous
end-users and modders.

When I designed my application's C++ Lua wrapper, I tried to emulate Lua's
object-oriented paradigm.  To call a function of a C++ object from Lua, you
need to pass the "self" object as the first argument. In other words, you
use Lua's "colon" operator. 

For example, given a class Foo with property "prop" and method "bar":

	foo = newFoo()
	foo.prop = 2

	-- explicit method call
	foo.bar(foo)

	-- use the ":" syntactic sugar
	foo:bar()

Thus, a C++ object exposed to Lua behaves rather like a Lua table that is
emulating an object.  (PIL 149-151)

However, it occurs to me that this isn't strictly necessary.  When my C++
object handles the __index request, it already knows what "self" is, because
it is passed in on the stack, along with the function name.  It is redundant
to require the object again as the first function argument.  My Lua code
could look like this:

	foo = newFoo()
	foo.prop = 2
	foo.bar()

Notice how this is much more intuitive to users of javascript, Java, C#, VB,
etc. etc.

I can still use a member function as a functor, but it is effectively bound
to the object you got it from:

	func = foo.bar
	func()


At least once a day I forget to type that pesky colon. It's driving me a
little nuts.  Before I forget my pain and subject end-users of my app to
this problem, I have to decide between two options:

1) Respect Lua's arguably idiosyncratic "colon" syntax in the interest of
consistency with the Lua language.

2) Re-write my C++ proxies to not require the "self" parameter.  The
advantage is that users who are not fluent in Lua won't have to deal with
the "colon" syntax, and I'll also make fewer mistakes in my script coding!


Here's another way to look at it:  Lua tables can be made to emulate
objects.  Should a userdata object masquerade as a Lua table emnulating an
object, or should it just "be an object"?

I'm curious to know what others think.  Is opinion divided, or is this
heresy?  Are there other pros and cons, alternatives, advice?

-Erik