我在 Allegro 5 中使用 Lua 和 LuaBridge。我决定将所有图形对象移植到 Lua,但遇到了一些问题:
被调用一次的字符类
Character = {sprite; AI}
function Character:new()
o = o or {} -- works!
setmetatable(o, self) -- works!
self.__index = self -- works!
return o -- works!
end
function Character:LoadSprite(filename)
self.sprite = self.sprite or Bitmap() -- works!
self.sprite:LoadFile(filename) -- works!
self.sprite.x = 0 -- works!
self.sprite.y = 0 --works!
end
function Character:SetX(xx)
self.sprite.x = xx -- maybe? cannot tell if it works or not.
end
function Character:AddBehavior(fname, cname)
self.AI = self.AI or Pattern()
self.AI:AddBehavior(fname, cname)
end
function Character:Draw()
self.sprite:Draw() -- works!
end
Foo = Character:new()
从主程序调用函数的 Lua 脚本:
function CoreInit() --called at initialization
Foo:LoadSprite("Image.png") -- works!
end
function CoreLogic() --called during logic cycle
Foo:SetX(50) -- does NOT work!
end
function CoreDraw() --called during drawing/rendering cycle
Foo:Draw() --works perfectly!
end
所以基本上,脚本用适当的坐标和图像初始化角色,并绘制它,但要么没有调用逻辑(它在逻辑循环中),要么改变 X 坐标的函数有问题。
此外,任务管理器建议每个周期存在约 30 KB 的内存泄漏,当我在 C++ 中使用图像对象时没有发生这种情况。
下面是通过 LuaBridge 导出到 Lua 的 Bitmap 结构的片段,以备不时之需:
void Bitmap::Register(lua_State*lua) {
luabridge::getGlobalNamespace(lua)
.beginClass<Bitmap>("Bitmap")
.addConstructor <void (*) (void)> ()
.addStaticData("scale", &Bitmap::scale)
.addFunction("LoadFile", &Bitmap::LoadFile)
.addFunction("Draw", &Bitmap::Draw)
.addData("x", &Bitmap::x)
.addData("y", &Bitmap::y)
.addData("w", &Bitmap::w)
.addData("h", &Bitmap::h)
.endClass();
}
void Bitmap::LoadFile(string file) {
name = file;
bitmap = al_load_bitmap(file.c_str());
w = al_get_bitmap_width(bitmap);
h = al_get_bitmap_height(bitmap);
}
void Bitmap::Draw() {
if (scale > 1)
al_draw_scaled_bitmap(bitmap, 0, 0, w, h, x * scale , y * scale, w * scale, h * scale, 0);
else
al_draw_bitmap(bitmap, x, y, 0);
}
Bitmap::Bitmap() : velocity(1) {
bitmap = NULL;
}
Bitmap::~Bitmap() {
name = "";
if (!bitmap)
al_destroy_bitmap(bitmap);
}
更新:我能够弄清楚的一件事是内存泄漏来自CoreLogic;我在 C++ 中注释掉了对它的调用,内存泄漏消失了,但是当我保持调用不变,但注释掉CoreLogic的内容时,泄漏仍然存在。嗯……
第二次更新:内存泄漏已被缩小到与人工智能有关的东西,我没有发布:
Pattern = {complete; timer; command; Files; Commands; itr; num}
function Pattern:new()
o = o or {}
o.Files = {}
o.Commands = {}
o.complete = false
o.timer = 0
o.itr = 1
o.num = 1
setmetatable(o, self)
self.__index = self
return o
end
function Pattern:AddBehavior(filename, commandname)
self.Files[self.num] = filename
self.Commands[self.num] = commandname
self.num = self.num + 1
end
function Pattern:DoBehavior()
self.command = self.Commands[self.itr]
dofile(self.Files[self.itr])
end
function Pattern:CheckBehavior()
if self.complete == true then
self.itr = self.itr + 1
self.timer = 0
self.complete = false
end
if itr >= num then
self.itr = 1
self.timer = 0
self.complete = false
end
end
function Pattern:Initialize()
self.itr = 1; self.timer = 0
self.complete = false
self.command = self.Commands[self.itr]
end
在CoreLogic函数中,它会调用Foo.AI:DoBehavior(),这完全没有做任何事情并导致内存泄漏。