views:

78

answers:

3

Ruby has this very interesting functionality in which when you create a class with 'Class.new' and assign it to a constant (uppercase), the language "magically" sets up the name of the class so it matches the constant.

# This is ruby code
MyRubyClass = Class.new(SuperClass)
puts MyRubyClass.name # "MyRubyClass"

It seems ruby "captures" the assignment and inserts sets the name on the anonymous class.

I'd like to know if there's a way to do something similar in Lua.

I've implemented my own class system, but for it to work I've got to specify the same name twice:

-- This is Lua code
MyLuaClass = class('MyLuaClass', SuperClass)
print(MyLuaClass.name) -- MyLuaClass

I'd like to get rid of that 'MyLuaClass' string. Is there any way to do this in Lua?

+2  A: 

You can eliminate one of the mentions of MyLuaClass...

> function class(name,superclass) _G[name] = {superclass=superclass} end
> class('MyLuaClass',33)
> =MyLuaClass
table: 0x10010b900
> =MyLuaClass.superclass
33
> 
Doug Currie
This was one of my first trails of thought. Another was using an __index method on class (which would be a table) - so it would go like this: class.MyLuaClass(superclass). But I really wanted to know about assignment capturing, if it was possible at all. +1 for your efforts.
egarcia
A: 

Not really. Lua is not an object-orientated language. It can behave like one sometimes. But far from every time. Classes are not special values in Lua. A table has the value you put in it, no more. The best you can do is manually set the key in _G from the class function and eliminate having to take the return value.

I guess that if it REALLY, REALLY bothers you, you could use debug.traceback(), get a stack trace, find the calling file, and parse it to find the variable name. Then set that. But that's more than a little overkill.

DeadMG
I don't want to make Lua behave like an object-oriented language every time. I apologize if I gave you that impression. I just wanted to know how to capture assignments. I'll keep searching.
egarcia
@egarcia: You can't capture assignments. Lua does not have a metatable entry for assignment. Assignment into a table, yes. Assignment in general, no.
DeadMG
+3  A: 

When assigning to global variables you can set a __newindex metamethod for the table of globals to catch assignments of class variables and do whatever is needed.

lhf
This looks possible, but not very efficient; I'll have to invoke a lua function every time a global assignment is done; might not be a big deal if global assignments are kept to a minimum. I'll give it a try, thanks for the hint.
egarcia
The cost of invoking a Lua function is not that much. If you had performance concerns, move to C or use LuaJIT. A few function calls, especially during this sort of set-up work, is negligible.
DeadMG
This was the best approach. Thanks!
egarcia