【Lua】モジュール
モジュールを記載したファイルをファイル名のオブジェクト(モジュール)
としてグローバル変数(_G)に設定し、パッケージに読み込みしたことを伝える
require関数からファイルを読み込み、モジュールからオブジェクトを生成する
下記のモジュールの機能は、生成毎に隠蔽されたIDを発行してIDを取得するものである
object.lua
local name = ... local base = {} _G[name] = base package.loaded[name] = base local counter = 0 function base:new(t) counter = counter + 1 local id = counter local class = {getID = function () return id end} local t = t or {} setmetatable(t, {__index = class}) return t end
test.lua
require("object") obj1 = object:new() print(obj1, "id:" .. obj1.getID()) -->table:xxxxxxxx id:1 obj2 = object:new{_name = "hoge"} function obj2:show() print(obj2, "id:" .. self.getID(), "name:" .. self._name) end obj2:show() -->table:xxxxxxxx id:2 name: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; }