tags:

views:

380

answers:

2

Would it be possible using Lua and SWIG and say an IInterface class, to implement that interface and instantiate it all within Lua? If so how would it be done?

+1  A: 

In the first place, C++ style interfaces does now make much sense in a language like Lua. For a Lua object to conform to an interface, it just need to contain definitions for all the functions in that interface. There is no need for any specific inheritance. For instance, if you have a C++ interface like this:

// Represents a generic bank account
class Account {
    virtual void deposit(double amount) = 0;
};

you can implement it in Lua without any specific inheritance specifications:

SavingsAccount = { balance = 0 }
SavingsAccount.deposit = function(amount)
    SavingsAccount.balance = SavingsAccount.balance + amount
end

-- Usage
a = SavingsAccount
a.balance = 100
a.deposit(1000)

In short, you don't need the C++ interface. If you need to extend the functionality of a C++ class from Lua, you should wrap that into a Lua object as described here and do "metatable" inheritance as explained here. Also read the section on Object Oriented Programming in the Lua manual.

Vijay Mathew
I'm aware of this tutorial and it does not implement what I want. It tells me that C++ class B inheriting from C++ class A can still be used in lua.But it would not tell me how to declare and instance lua class C inheriting from c++ class B?
Tom J Nowell
@Tom J Nowell I have updated the answer.
Vijay Mathew
Well I figure that, the problem here is to implement it this way I would have to implement it using functions in a lua file, coupled with my own lua based object handler. I already have a C++ object handler, and I would rather allow my lua objects to work within this existing infrastructure as such an extra layer would strip out a tonne of architectural stuff and dramatically increase overhead in areas as a result.
Tom J Nowell
For example, events, In the desired system, only the lua objects that desired notification of events would get them, under the workaround I said above, all events would need ot be intercepted, and then the code reimplemented, and I would have a C and a lua implementation of the same code with the added overhead and architectual complexity.
Tom J Nowell
What I would like is to be able to take the Savings Account example above and submit the 'a' object itself and handle it around in the C side of the program as if it were a C object.
Tom J Nowell
A: 

Store the table in a c++ class by holding a pointer to the lua state, and the reference returned for the table as specified using this API:

http://www.lua.org/pil/27.3.2.html

Then when a method on the wrapper class is called, push the referenced object onto the stack and do the necessary function call

Tom J Nowell