【Lua】継承
継承には、メタテーブルである__indexフィールド(子)に親を設定する
子がメンバを呼び出したときにメタテーブルを検索してメンバがなければ
親の持つメタテーブルを参照する
test.lua
-->既定クラスを定義する Base = {} -->生成関数を定義する function Base:new(t) t = t or {} setmetatable(t, self) self.__index = self --setmetatable(t, {__index = self}) -->左記でも可 return t end -->Baseを継承したAを定義する -->newの引数にメンバとなるテーブルを渡す A = Base:new{_name = "no name"} -->メンバ関数を定義する function A:setName(x) self._name = x end function A:show() print("name:" .. self._name) end -->Aを継承したBを定義する B = A:new{_age = 0} function B:setAge(x) self._age = x end -->Aで定義したshow関数をオーバーライドする function B:show() print("name:" .. self._name, "age:" .. self._age) end A:setName("A") A:show() -->name:A B:setName("B") B:setAge(3) B:show() -->name:B age:3
test.cpp
#include <iostream> #include <lua.hpp> using namespace std; void test(char *file) { auto L = luaL_newstate(); luaL_openlibs(L); if (luaL_dofile(L, file)) { cout << lua_tostring(L, lua_gettop(L)) << endl; lua_close(L); getchar(); return; } lua_close(L); getchar(); } int main(int argc, char *argv[]) { test("test.lua"); return 0; }