【Lua】プライベートメンバを持つクラス
ローカル内に自身のテーブル(メンバ)を定義して、
そのテーブルに対する公開メソッドとなるテーブル(インターフェイス)を返却する
Luaのオブジェクトの基本設計ではプライベート機構は用意されていない
これは、オブジェクトの汎用性(テーブル)を意図しているためである
また、大規模なプログラムを想定するものではないので必要以上に冗長となることや
人為的に制限を課すことを避けている
アクセスしたくないものはアクセスしなければ良いお話である
このような設計が可能であるというLuaの柔軟性や、プログラムである種の問題に
対する解決策になる場合の為に纏めておく
test.lua
function newClass (name) local self = {_name = name} local set = function (n) self._name = n end local get = function () return self._name end local check = function () return nil ~= self._name end -->非公開メソッド local show = function () if check() then print(self._name) else print "no name" end end return { set = set, get = get, show = show } end c = newClass() c.show() -->no name c.set("hoge") c.show() -->hoge print(c.get()) -->hoge
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; }