Implementing and inheriting from C++ classes in Lua using SWIG

非 Y 不嫁゛ 提交于 2020-01-24 21:04:29

问题


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:


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.




回答2:


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



来源:https://stackoverflow.com/questions/1782337/implementing-and-inheriting-from-c-classes-in-lua-using-swig

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!