Implementing and inheriting from C++ classes in Lua using SWIG
Would it be possible using Lua and SWIG and say an IInterface class, to implement that interface and instantiate 开发者_StackOverflow社区it all within Lua? If so how would it be done?
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.
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
精彩评论