SWORD25: Enforced code naming conventions in script/*

svn-id: r53391
This commit is contained in:
Eugene Sandulenko 2010-10-03 13:25:22 +00:00
parent 1e15d8efb7
commit 54ccc8f4c9
17 changed files with 299 additions and 435 deletions

View File

@ -152,10 +152,10 @@ bool MoviePlayer::registerScriptBindings() {
BS_ASSERT(pKernel);
ScriptEngine *pScript = static_cast<ScriptEngine *>(pKernel->GetService("script"));
BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->GetScriptObject());
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L);
if (!LuaBindhelper::AddFunctionsToLib(L, LIBRARY_NAME, LIBRARY_FUNCTIONS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, LIBRARY_NAME, LIBRARY_FUNCTIONS)) return false;
return true;
}

View File

@ -119,7 +119,7 @@ static void *my_checkudata(lua_State *L, int ud, const char *tname) {
if (p != NULL) { /* value is a userdata? */
if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
// lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
LuaBindhelper::GetMetatable(L, tname);
LuaBindhelper::getMetatable(L, tname);
if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */
lua_settop(L, top);
return p;
@ -163,7 +163,7 @@ static int NewAnimationTemplate(lua_State *L) {
if (AnimationTemplatePtr && AnimationTemplatePtr->isValid()) {
NewUintUserData(L, AnimationTemplateHandle);
//luaL_getmetatable(L, ANIMATION_TEMPLATE_CLASS_NAME);
LuaBindhelper::GetMetatable(L, ANIMATION_TEMPLATE_CLASS_NAME);
LuaBindhelper::getMetatable(L, ANIMATION_TEMPLATE_CLASS_NAME);
BS_ASSERT(!lua_isnil(L, -1));
lua_setmetatable(L, -2);
} else {
@ -301,7 +301,7 @@ static int Init(lua_State *L) {
NewUintUserData(L, MainPanelPtr->getHandle());
BS_ASSERT(!lua_isnil(L, -1));
// luaL_getmetatable(L, PANEL_CLASS_NAME);
LuaBindhelper::GetMetatable(L, PANEL_CLASS_NAME);
LuaBindhelper::getMetatable(L, PANEL_CLASS_NAME);
BS_ASSERT(!lua_isnil(L, -1));
lua_setmetatable(L, -2);
@ -671,7 +671,7 @@ static int RO_AddPanel(lua_State *L) {
if (PanelPtr.isValid()) {
NewUintUserData(L, PanelPtr->getHandle());
// luaL_getmetatable(L, PANEL_CLASS_NAME);
LuaBindhelper::GetMetatable(L, PANEL_CLASS_NAME);
LuaBindhelper::getMetatable(L, PANEL_CLASS_NAME);
BS_ASSERT(!lua_isnil(L, -1));
lua_setmetatable(L, -2);
} else
@ -689,7 +689,7 @@ static int RO_AddBitmap(lua_State *L) {
if (BitmaPtr.isValid()) {
NewUintUserData(L, BitmaPtr->getHandle());
// luaL_getmetatable(L, BITMAP_CLASS_NAME);
LuaBindhelper::GetMetatable(L, BITMAP_CLASS_NAME);
LuaBindhelper::getMetatable(L, BITMAP_CLASS_NAME);
BS_ASSERT(!lua_isnil(L, -1));
lua_setmetatable(L, -2);
} else
@ -711,7 +711,7 @@ static int RO_AddText(lua_State *L) {
if (TextPtr.isValid()) {
NewUintUserData(L, TextPtr->getHandle());
// luaL_getmetatable(L, TEXT_CLASS_NAME);
LuaBindhelper::GetMetatable(L, TEXT_CLASS_NAME);
LuaBindhelper::getMetatable(L, TEXT_CLASS_NAME);
BS_ASSERT(!lua_isnil(L, -1));
lua_setmetatable(L, -2);
} else
@ -735,7 +735,7 @@ static int RO_AddAnimation(lua_State *L) {
if (AnimationPtr.isValid()) {
NewUintUserData(L, AnimationPtr->getHandle());
// luaL_getmetatable(L, ANIMATION_CLASS_NAME);
LuaBindhelper::GetMetatable(L, ANIMATION_CLASS_NAME);
LuaBindhelper::getMetatable(L, ANIMATION_CLASS_NAME);
BS_ASSERT(!lua_isnil(L, -1));
lua_setmetatable(L, -2);
@ -1246,8 +1246,8 @@ static int A_IsPlaying(lua_State *L) {
// -----------------------------------------------------------------------------
static bool AnimationLoopPointCallback(uint Handle) {
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->GetScriptObject());
LoopPointCallbackPtr->InvokeCallbackFunctions(L, Handle);
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject());
LoopPointCallbackPtr->invokeCallbackFunctions(L, Handle);
return true;
}
@ -1260,7 +1260,7 @@ static int A_RegisterLoopPointCallback(lua_State *L) {
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_pushvalue(L, 2);
LoopPointCallbackPtr->RegisterCallbackFunction(L, AnimationPtr->getHandle());
LoopPointCallbackPtr->registerCallbackFunction(L, AnimationPtr->getHandle());
return 0;
}
@ -1273,7 +1273,7 @@ static int A_UnregisterLoopPointCallback(lua_State *L) {
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_pushvalue(L, 2);
LoopPointCallbackPtr->UnregisterCallbackFunction(L, AnimationPtr->getHandle());
LoopPointCallbackPtr->unregisterCallbackFunction(L, AnimationPtr->getHandle());
return 0;
}
@ -1284,8 +1284,8 @@ static bool AnimationActionCallback(uint Handle) {
RenderObjectPtr<Animation> AnimationPtr(Handle);
if (AnimationPtr.isValid()) {
ActionCallbackPtr->Action = AnimationPtr->GetCurrentAction();
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->GetScriptObject());
ActionCallbackPtr->InvokeCallbackFunctions(L, AnimationPtr->getHandle());
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject());
ActionCallbackPtr->invokeCallbackFunctions(L, AnimationPtr->getHandle());
}
return true;
@ -1299,7 +1299,7 @@ static int A_RegisterActionCallback(lua_State *L) {
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_pushvalue(L, 2);
ActionCallbackPtr->RegisterCallbackFunction(L, AnimationPtr->getHandle());
ActionCallbackPtr->registerCallbackFunction(L, AnimationPtr->getHandle());
return 0;
}
@ -1312,7 +1312,7 @@ static int A_UnregisterActionCallback(lua_State *L) {
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_pushvalue(L, 2);
ActionCallbackPtr->UnregisterCallbackFunction(L, AnimationPtr->getHandle());
ActionCallbackPtr->unregisterCallbackFunction(L, AnimationPtr->getHandle());
return 0;
}
@ -1320,8 +1320,8 @@ static int A_UnregisterActionCallback(lua_State *L) {
// -----------------------------------------------------------------------------
static bool AnimationDeleteCallback(uint Handle) {
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->GetScriptObject());
LoopPointCallbackPtr->RemoveAllObjectCallbacks(L, Handle);
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject());
LoopPointCallbackPtr->removeAllObjectCallbacks(L, Handle);
return true;
}
@ -1527,22 +1527,22 @@ bool GraphicEngine::RegisterScriptBindings() {
BS_ASSERT(pKernel);
ScriptEngine *pScript = static_cast<ScriptEngine *>(pKernel->GetService("script"));
BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->GetScriptObject());
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L);
if (!LuaBindhelper::AddMethodsToClass(L, BITMAP_CLASS_NAME, RENDEROBJECT_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, ANIMATION_CLASS_NAME, RENDEROBJECT_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, PANEL_CLASS_NAME, RENDEROBJECT_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, TEXT_CLASS_NAME, RENDEROBJECT_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, BITMAP_CLASS_NAME, RENDEROBJECT_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, ANIMATION_CLASS_NAME, RENDEROBJECT_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, PANEL_CLASS_NAME, RENDEROBJECT_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, TEXT_CLASS_NAME, RENDEROBJECT_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, PANEL_CLASS_NAME, PANEL_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, BITMAP_CLASS_NAME, BITMAP_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, TEXT_CLASS_NAME, TEXT_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, ANIMATION_CLASS_NAME, ANIMATION_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, PANEL_CLASS_NAME, PANEL_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, BITMAP_CLASS_NAME, BITMAP_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, TEXT_CLASS_NAME, TEXT_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, ANIMATION_CLASS_NAME, ANIMATION_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, ANIMATION_TEMPLATE_CLASS_NAME, ANIMATION_TEMPLATE_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, ANIMATION_TEMPLATE_CLASS_NAME, ANIMATION_TEMPLATE_METHODS)) return false;
if (!LuaBindhelper::AddFunctionsToLib(L, GFX_LIBRARY_NAME, GFX_FUNCTIONS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, GFX_LIBRARY_NAME, GFX_FUNCTIONS)) return false;
LoopPointCallbackPtr.reset(new LuaCallback(L));
ActionCallbackPtr.reset(new ActionCallback(L));

View File

@ -245,15 +245,15 @@ static int SetMouseY(lua_State *L) {
static void TheCharacterCallback(int Character) {
CharacterCallbackPtr->Character = static_cast<byte>(Character);
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->GetScriptObject());
CharacterCallbackPtr->InvokeCallbackFunctions(L, 1);
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject());
CharacterCallbackPtr->invokeCallbackFunctions(L, 1);
}
// -----------------------------------------------------------------------------
static int RegisterCharacterCallback(lua_State *L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
CharacterCallbackPtr->RegisterCallbackFunction(L, 1);
CharacterCallbackPtr->registerCallbackFunction(L, 1);
return 0;
}
@ -262,7 +262,7 @@ static int RegisterCharacterCallback(lua_State *L) {
static int UnregisterCharacterCallback(lua_State *L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
CharacterCallbackPtr->UnregisterCallbackFunction(L, 1);
CharacterCallbackPtr->unregisterCallbackFunction(L, 1);
return 0;
}
@ -271,15 +271,15 @@ static int UnregisterCharacterCallback(lua_State *L) {
static void TheCommandCallback(int Command) {
CommandCallbackPtr->Command = static_cast<InputEngine::KEY_COMMANDS>(Command);
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->GetScriptObject());
CommandCallbackPtr->InvokeCallbackFunctions(L, 1);
lua_State *L = static_cast<lua_State *>(Kernel::GetInstance()->GetScript()->getScriptObject());
CommandCallbackPtr->invokeCallbackFunctions(L, 1);
}
// -----------------------------------------------------------------------------
static int RegisterCommandCallback(lua_State *L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
CommandCallbackPtr->RegisterCallbackFunction(L, 1);
CommandCallbackPtr->registerCallbackFunction(L, 1);
return 0;
}
@ -288,7 +288,7 @@ static int RegisterCommandCallback(lua_State *L) {
static int UnregisterCommandCallback(lua_State *L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
CommandCallbackPtr->UnregisterCallbackFunction(L, 1);
CommandCallbackPtr->unregisterCallbackFunction(L, 1);
return 0;
}
@ -340,11 +340,11 @@ bool InputEngine::registerScriptBindings() {
BS_ASSERT(pKernel);
ScriptEngine *pScript = static_cast<ScriptEngine *>(pKernel->GetService("script"));
BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->GetScriptObject());
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L);
if (!LuaBindhelper::AddFunctionsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_FUNCTIONS)) return false;
if (!LuaBindhelper::AddConstantsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_CONSTANTS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_FUNCTIONS)) return false;
if (!LuaBindhelper::addConstantsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_CONSTANTS)) return false;
CharacterCallbackPtr = Common::SharedPtr<CharacterCallbackClass>(new CharacterCallbackClass(L));
CommandCallbackPtr = Common::SharedPtr<CommandCallbackClass>(new CommandCallbackClass(L));

View File

@ -86,7 +86,7 @@ Kernel::Kernel() :
// Initialise the script engine
ScriptEngine *pScript = static_cast<ScriptEngine *>(NewService("script", "lua"));
if (!pScript || !pScript->Init()) {
if (!pScript || !pScript->init()) {
_InitSuccess = false;
return;
}

View File

@ -174,7 +174,7 @@ static int ExecuteFile(lua_State *L) {
ScriptEngine *pSE = static_cast<ScriptEngine *>(pKernel->GetService("script"));
BS_ASSERT(pSE);
lua_pushbooleancpp(L, pSE->ExecuteFile(luaL_checkstring(L, 1)));
lua_pushbooleancpp(L, pSE->executeFile(luaL_checkstring(L, 1)));
return 0;
}
@ -725,13 +725,13 @@ static const luaL_reg PERSISTENCE_FUNCTIONS[] = {
bool Kernel::_RegisterScriptBindings() {
ScriptEngine *pScript = static_cast<ScriptEngine *>(GetService("script"));
BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->GetScriptObject());
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L);
if (!LuaBindhelper::AddFunctionsToLib(L, KERNEL_LIBRARY_NAME, KERNEL_FUNCTIONS)) return false;
if (!LuaBindhelper::AddFunctionsToLib(L, WINDOW_LIBRARY_NAME, WINDOW_FUNCTIONS)) return false;
if (!LuaBindhelper::AddFunctionsToLib(L, RESOURCE_LIBRARY_NAME, RESOURCE_FUNCTIONS)) return false;
if (!LuaBindhelper::AddFunctionsToLib(L, PERSISTENCE_LIBRARY_NAME, PERSISTENCE_FUNCTIONS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, KERNEL_LIBRARY_NAME, KERNEL_FUNCTIONS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, WINDOW_LIBRARY_NAME, WINDOW_FUNCTIONS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, RESOURCE_LIBRARY_NAME, RESOURCE_FUNCTIONS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, PERSISTENCE_LIBRARY_NAME, PERSISTENCE_FUNCTIONS)) return false;
return true;
}

View File

@ -71,7 +71,7 @@ static void *my_checkudata(lua_State *L, int ud, const char *tname) {
if (p != NULL) { /* value is a userdata? */
if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
// lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
LuaBindhelper::GetMetatable(L, tname);
LuaBindhelper::getMetatable(L, tname);
/* does it have the correct mt? */
if (lua_rawequal(L, -1, -2)) {
lua_settop(L, top);
@ -273,7 +273,7 @@ static void NewUserdataRegion(lua_State *L, const char *ClassName) {
NewUintUserData(L, RegionHandle);
// luaL_getmetatable(L, ClassName);
LuaBindhelper::GetMetatable(L, ClassName);
LuaBindhelper::getMetatable(L, ClassName);
BS_ASSERT(!lua_isnil(L, -1));
lua_setmetatable(L, -2);
}
@ -540,17 +540,17 @@ bool Geometry::_RegisterScriptBindings() {
BS_ASSERT(pKernel);
ScriptEngine *pScript = static_cast<ScriptEngine *>(pKernel->GetService("script"));
BS_ASSERT(pScript);
lua_State *L = static_cast< lua_State *>(pScript->GetScriptObject());
lua_State *L = static_cast< lua_State *>(pScript->getScriptObject());
BS_ASSERT(L);
if (!LuaBindhelper::AddMethodsToClass(L, REGION_CLASS_NAME, REGION_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, WALKREGION_CLASS_NAME, REGION_METHODS)) return false;
if (!LuaBindhelper::AddMethodsToClass(L, WALKREGION_CLASS_NAME, WALKREGION_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, REGION_CLASS_NAME, REGION_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, WALKREGION_CLASS_NAME, REGION_METHODS)) return false;
if (!LuaBindhelper::addMethodsToClass(L, WALKREGION_CLASS_NAME, WALKREGION_METHODS)) return false;
if (!LuaBindhelper::SetClassGCHandler(L, REGION_CLASS_NAME, R_Delete)) return false;
if (!LuaBindhelper::SetClassGCHandler(L, WALKREGION_CLASS_NAME, R_Delete)) return false;
if (!LuaBindhelper::setClassGCHandler(L, REGION_CLASS_NAME, R_Delete)) return false;
if (!LuaBindhelper::setClassGCHandler(L, WALKREGION_CLASS_NAME, R_Delete)) return false;
if (!LuaBindhelper::AddFunctionsToLib(L, GEO_LIBRARY_NAME, GEO_FUNCTIONS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, GEO_LIBRARY_NAME, GEO_FUNCTIONS)) return false;
return true;
}

View File

@ -203,10 +203,10 @@ bool PackageManager::registerScriptBindings() {
BS_ASSERT(pKernel);
ScriptEngine *pScript = static_cast<ScriptEngine *>(pKernel->GetService("script"));
BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->GetScriptObject());
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L);
if (!LuaBindhelper::AddFunctionsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_FUNCTIONS))
if (!LuaBindhelper::addFunctionsToLib(L, PACKAGE_LIBRARY_NAME, PACKAGE_FUNCTIONS))
return false;
return true;

View File

@ -32,18 +32,12 @@
*
*/
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/script/luascript.h"
#include "sword25/script/luabindhelper.h"
// -----------------------------------------------------------------------------
namespace Sword25 {
static int Warning(lua_State *L) {
static int warning(lua_State *L) {
#ifdef DEBUG
int __startStackDepth = lua_gettop(L);
#endif
@ -63,20 +57,17 @@ static int Warning(lua_State *L) {
return 0;
}
// -----------------------------------------------------------------------------
static const luaL_reg GLOBAL_FUNCTIONS[] = {
{"warning", Warning},
{"warning", warning},
{0, 0}
};
// -----------------------------------------------------------------------------
bool LuaScriptEngine::registerStandardLibExtensions() {
lua_State *L = _state;
BS_ASSERT(_state);
bool LuaScriptEngine::RegisterStandardLibExtensions() {
lua_State *L = m_State;
BS_ASSERT(m_State);
if (!LuaBindhelper::AddFunctionsToLib(L, "", GLOBAL_FUNCTIONS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, "", GLOBAL_FUNCTIONS))
return false;
return true;
}

View File

@ -32,25 +32,20 @@
*
*/
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/kernel.h"
#include "sword25/script/luabindhelper.h"
#include "sword25/script/luascript.h"
#define BS_LOG_PREFIX "LUABINDHELPER"
// -----------------------------------------------------------------------------
namespace {
const char *METATABLES_TABLE_NAME = "__METATABLES";
const char *PERMANENTS_TABLE_NAME = "Permanents";
bool RegisterPermanent(lua_State *L, const Common::String &Name) {
bool registerPermanent(lua_State *L, const Common::String &name) {
// A C function has to be on the stack
if (!lua_iscfunction(L, -1)) return false;
if (!lua_iscfunction(L, -1))
return false;
// Make sure that the Permanents-Table is on top of the stack
lua_getfield(L, LUA_REGISTRYINDEX, PERMANENTS_TABLE_NAME);
@ -71,7 +66,7 @@ bool RegisterPermanent(lua_State *L, const Common::String &Name) {
// C function with the name of an index in the Permanents-Table
lua_insert(L, -2);
lua_setfield(L, -2, Name.c_str());
lua_setfield(L, -2, name.c_str());
// Remove the Permanents-Table from the stack
lua_pop(L, 1);
@ -82,8 +77,6 @@ bool RegisterPermanent(lua_State *L, const Common::String &Name) {
namespace Sword25 {
// -----------------------------------------------------------------------------
/**
* Registers a set of functions into a Lua library.
* @param L A pointer to the Lua VM
@ -93,38 +86,38 @@ namespace Sword25 {
* The array must be terminated with the enry (0, 0)
* @return Returns true if successful, otherwise false.
*/
bool LuaBindhelper::AddFunctionsToLib(lua_State *L, const Common::String &LibName, const luaL_reg *Functions) {
bool LuaBindhelper::addFunctionsToLib(lua_State *L, const Common::String &libName, const luaL_reg *functions) {
#ifdef DEBUG
int __startStackDepth = lua_gettop(L);
#endif
// If the table name is empty, the functions are to be added to the global namespace
if (LibName.size() == 0) {
for (; Functions->name; ++Functions) {
lua_pushstring(L, Functions->name);
lua_pushcclosure(L, Functions->func, 0);
if (libName.size() == 0) {
for (; functions->name; ++functions) {
lua_pushstring(L, functions->name);
lua_pushcclosure(L, functions->func, 0);
lua_settable(L, LUA_GLOBALSINDEX);
// Function is being permanently registed, so persistence can be ignored
lua_pushstring(L, Functions->name);
lua_pushstring(L, functions->name);
lua_gettable(L, LUA_GLOBALSINDEX);
RegisterPermanent(L, Functions->name);
registerPermanent(L, functions->name);
}
} else { // If the table name is not empty, the functions are added to the given table
// Ensure that the library table exists
if (!_CreateTable(L, LibName)) return false;
if (!createTable(L, libName)) return false;
// Register each function into the table
for (; Functions->name; ++Functions) {
for (; functions->name; ++functions) {
// Function registration
lua_pushstring(L, Functions->name);
lua_pushcclosure(L, Functions->func, 0);
lua_pushstring(L, functions->name);
lua_pushcclosure(L, functions->func, 0);
lua_settable(L, -3);
// Function is being permanently registed, so persistence can be ignored
lua_pushstring(L, Functions->name);
lua_pushstring(L, functions->name);
lua_gettable(L, -2);
RegisterPermanent(L, LibName + "." + Functions->name);
registerPermanent(L, libName + "." + functions->name);
}
// Remove the library table from the Lua stack
@ -138,8 +131,6 @@ bool LuaBindhelper::AddFunctionsToLib(lua_State *L, const Common::String &LibNam
return true;
}
// -----------------------------------------------------------------------------
/**
* Adds a set of constants to the Lua library
* @param L A pointer to the Lua VM
@ -149,28 +140,28 @@ bool LuaBindhelper::AddFunctionsToLib(lua_State *L, const Common::String &LibNam
* The array must be terminated with the enry (0, 0)
* @return Returns true if successful, otherwise false.
*/
bool LuaBindhelper::AddConstantsToLib(lua_State *L, const Common::String &LibName, const lua_constant_reg *Constants) {
bool LuaBindhelper::addConstantsToLib(lua_State *L, const Common::String &libName, const lua_constant_reg *constants) {
#ifdef DEBUG
int __startStackDepth = lua_gettop(L);
#endif
// If the table is empty, the constants are added to the global namespace
if (LibName.size() == 0) {
for (; Constants->Name; ++Constants) {
lua_pushstring(L, Constants->Name);
lua_pushnumber(L, Constants->Value);
if (libName.size() == 0) {
for (; constants->Name; ++constants) {
lua_pushstring(L, constants->Name);
lua_pushnumber(L, constants->Value);
lua_settable(L, LUA_GLOBALSINDEX);
}
}
// If the table name is nto empty, the constants are added to that table
else {
// Ensure that the library table exists
if (!_CreateTable(L, LibName)) return false;
if (!createTable(L, libName)) return false;
// Register each constant in the table
for (; Constants->Name; ++Constants) {
lua_pushstring(L, Constants->Name);
lua_pushnumber(L, Constants->Value);
for (; constants->Name; ++constants) {
lua_pushstring(L, constants->Name);
lua_pushnumber(L, constants->Value);
lua_settable(L, -3);
}
@ -185,8 +176,6 @@ bool LuaBindhelper::AddConstantsToLib(lua_State *L, const Common::String &LibNam
return true;
}
// -----------------------------------------------------------------------------
/**
* Adds a set of methods to a Lua class
* @param L A pointer to the Lua VM
@ -196,24 +185,24 @@ bool LuaBindhelper::AddConstantsToLib(lua_State *L, const Common::String &LibNam
* The array must be terminated with the enry (0, 0)
* @return Returns true if successful, otherwise false.
*/
bool LuaBindhelper::AddMethodsToClass(lua_State *L, const Common::String &ClassName, const luaL_reg *Methods) {
bool LuaBindhelper::addMethodsToClass(lua_State *L, const Common::String &className, const luaL_reg *methods) {
#ifdef DEBUG
int __startStackDepth = lua_gettop(L);
#endif
// Load the metatable onto the Lua stack
if (!GetMetatable(L, ClassName)) return false;
if (!getMetatable(L, className)) return false;
// Register each method in the Metatable
for (; Methods->name; ++Methods) {
lua_pushstring(L, Methods->name);
lua_pushcclosure(L, Methods->func, 0);
for (; methods->name; ++methods) {
lua_pushstring(L, methods->name);
lua_pushcclosure(L, methods->func, 0);
lua_settable(L, -3);
// Function is being permanently registed, so persistence can be ignored
lua_pushstring(L, Methods->name);
lua_pushstring(L, methods->name);
lua_gettable(L, -2);
RegisterPermanent(L, ClassName + "." + Methods->name);
registerPermanent(L, className + "." + methods->name);
}
// Remove the metatable from the stack
@ -226,8 +215,6 @@ bool LuaBindhelper::AddMethodsToClass(lua_State *L, const Common::String &ClassN
return true;
}
// -----------------------------------------------------------------------------
/**
* Sets the garbage collector callback method when items of a particular class are deleted
* @param L A pointer to the Lua VM
@ -236,13 +223,13 @@ bool LuaBindhelper::AddMethodsToClass(lua_State *L, const Common::String &ClassN
* @param GCHandler A function pointer
* @return Returns true if successful, otherwise false.
*/
bool LuaBindhelper::SetClassGCHandler(lua_State *L, const Common::String &ClassName, lua_CFunction GCHandler) {
bool LuaBindhelper::setClassGCHandler(lua_State *L, const Common::String &className, lua_CFunction GCHandler) {
#ifdef DEBUG
int __startStackDepth = lua_gettop(L);
#endif
// Load the metatable onto the Lua stack
if (!GetMetatable(L, ClassName)) return false;
if (!getMetatable(L, className)) return false;
// Add the GC handler to the Metatable
lua_pushstring(L, "__gc");
@ -252,7 +239,7 @@ bool LuaBindhelper::SetClassGCHandler(lua_State *L, const Common::String &ClassN
// Function is being permanently registed, so persistence can be ignored
lua_pushstring(L, "__gc");
lua_gettable(L, -2);
RegisterPermanent(L, ClassName + ".__gc");
registerPermanent(L, className + ".__gc");
// Remove the metatable from the stack
lua_pop(L, 1);
@ -266,10 +253,8 @@ bool LuaBindhelper::SetClassGCHandler(lua_State *L, const Common::String &ClassN
} // End of namespace Sword25
// -----------------------------------------------------------------------------
namespace {
void PushMetatableTable(lua_State *L) {
void pushMetatableTable(lua_State *L) {
// Push the Metatable table onto the stack
lua_getglobal(L, METATABLES_TABLE_NAME);
@ -288,12 +273,12 @@ void PushMetatableTable(lua_State *L) {
namespace Sword25 {
bool LuaBindhelper::GetMetatable(lua_State *L, const Common::String &TableName) {
bool LuaBindhelper::getMetatable(lua_State *L, const Common::String &tableName) {
// Push the Metatable table onto the stack
PushMetatableTable(L);
pushMetatableTable(L);
// Versuchen, die gewünschte Metatabelle auf den Stack zu legen. Wenn sie noch nicht existiert, muss sie erstellt werden.
lua_getfield(L, -1, TableName.c_str());
lua_getfield(L, -1, tableName.c_str());
if (lua_isnil(L, -1)) {
// Pop nil from stack
lua_pop(L, 1);
@ -311,7 +296,7 @@ bool LuaBindhelper::GetMetatable(lua_State *L, const Common::String &TableName)
// Set the table name and push it onto the stack
lua_pushvalue(L, -1);
lua_setfield(L, -3, TableName.c_str());
lua_setfield(L, -3, tableName.c_str());
}
// Remove the Metatable table from the stack
@ -320,29 +305,27 @@ bool LuaBindhelper::GetMetatable(lua_State *L, const Common::String &TableName)
return true;
}
// -----------------------------------------------------------------------------
bool LuaBindhelper::createTable(lua_State *L, const Common::String &tableName) {
const char *partBegin = tableName.c_str();
bool LuaBindhelper::_CreateTable(lua_State *L, const Common::String &TableName) {
const char *PartBegin = TableName.c_str();
while (PartBegin - TableName.c_str() < (int)TableName.size()) {
const char *PartEnd = strchr(PartBegin, '.');
if (!PartEnd)
PartEnd = PartBegin + strlen(PartBegin);
Common::String SubTableName(PartBegin, PartEnd);
while (partBegin - tableName.c_str() < (int)tableName.size()) {
const char *partEnd = strchr(partBegin, '.');
if (!partEnd)
partEnd = partBegin + strlen(partBegin);
Common::String subTableName(partBegin, partEnd);
// Tables with an empty string as the name are not allowed
if (SubTableName.size() == 0)
if (subTableName.size() == 0)
return false;
// Verify that the table with the name already exists
// The first round will be searched in the global namespace, with later passages
// in the corresponding parent table in the stack
if (PartBegin == TableName.c_str()) {
lua_pushstring(L, SubTableName.c_str());
if (partBegin == tableName.c_str()) {
lua_pushstring(L, subTableName.c_str());
lua_gettable(L, LUA_GLOBALSINDEX);
} else {
lua_pushstring(L, SubTableName.c_str());
lua_pushstring(L, subTableName.c_str());
lua_gettable(L, -2);
if (!lua_isnil(L, -1))
lua_remove(L, -2);
@ -355,9 +338,9 @@ bool LuaBindhelper::_CreateTable(lua_State *L, const Common::String &TableName)
// Create new table
lua_newtable(L);
lua_pushstring(L, SubTableName.c_str());
lua_pushstring(L, subTableName.c_str());
lua_pushvalue(L, -2);
if (PartBegin == TableName.c_str())
if (partBegin == tableName.c_str())
lua_settable(L, LUA_GLOBALSINDEX);
else {
lua_settable(L, -4);
@ -365,7 +348,7 @@ bool LuaBindhelper::_CreateTable(lua_State *L, const Common::String &TableName)
}
}
PartBegin = PartEnd + 1;
partBegin = partEnd + 1;
}
return true;
@ -374,18 +357,18 @@ bool LuaBindhelper::_CreateTable(lua_State *L, const Common::String &TableName)
} // End of namespace Sword25
namespace {
Common::String GetLuaValueInfo(lua_State *L, int StackIndex) {
switch (lua_type(L, StackIndex)) {
Common::String getLuaValueInfo(lua_State *L, int stackIndex) {
switch (lua_type(L, stackIndex)) {
case LUA_TNUMBER:
lua_pushstring(L, lua_tostring(L, StackIndex));
lua_pushstring(L, lua_tostring(L, stackIndex));
break;
case LUA_TSTRING:
lua_pushfstring(L, "\"%s\"", lua_tostring(L, StackIndex));
lua_pushfstring(L, "\"%s\"", lua_tostring(L, stackIndex));
break;
case LUA_TBOOLEAN:
lua_pushstring(L, (lua_toboolean(L, StackIndex) ? "true" : "false"));
lua_pushstring(L, (lua_toboolean(L, stackIndex) ? "true" : "false"));
break;
case LUA_TNIL:
@ -393,27 +376,27 @@ Common::String GetLuaValueInfo(lua_State *L, int StackIndex) {
break;
default:
lua_pushfstring(L, "%s: %p", luaL_typename(L, StackIndex), lua_topointer(L, StackIndex));
lua_pushfstring(L, "%s: %p", luaL_typename(L, stackIndex), lua_topointer(L, stackIndex));
break;
}
Common::String Result(lua_tostring(L, -1));
Common::String result(lua_tostring(L, -1));
lua_pop(L, 1);
return Result;
return result;
}
}
namespace Sword25 {
Common::String LuaBindhelper::StackDump(lua_State *L) {
Common::String LuaBindhelper::stackDump(lua_State *L) {
Common::String oss;
int i = lua_gettop(L);
oss += "------------------- Stack Dump -------------------\n";
while (i) {
oss += i + ": " + GetLuaValueInfo(L, i) + "\n";
oss += i + ": " + getLuaValueInfo(L, i) + "\n";
i--;
}
@ -422,7 +405,7 @@ Common::String LuaBindhelper::StackDump(lua_State *L) {
return oss;
}
Common::String LuaBindhelper::TableDump(lua_State *L) {
Common::String LuaBindhelper::tableDump(lua_State *L) {
Common::String oss;
oss += "------------------- Table Dump -------------------\n";
@ -430,7 +413,7 @@ Common::String LuaBindhelper::TableDump(lua_State *L) {
lua_pushnil(L);
while (lua_next(L, -2) != 0) {
// Get the value of the current element on top of the stack, including the index
oss += GetLuaValueInfo(L, -2) + " : " + GetLuaValueInfo(L, -1) + "\n";
oss += getLuaValueInfo(L, -2) + " : " + getLuaValueInfo(L, -1) + "\n";
// Pop value from the stack. The index is then ready for the next call to lua_next()
lua_pop(L, 1);

View File

@ -70,7 +70,7 @@ public:
* The array must be terminated with the enry (0, 0)
* @return Returns true if successful, otherwise false.
*/
static bool AddFunctionsToLib(lua_State *L, const Common::String &LibName, const luaL_reg *Functions);
static bool addFunctionsToLib(lua_State *L, const Common::String &libName, const luaL_reg *functions);
/**
* Adds a set of constants to the Lua library
@ -81,7 +81,7 @@ public:
* The array must be terminated with the enry (0, 0)
* @return Returns true if successful, otherwise false.
*/
static bool AddConstantsToLib(lua_State *L, const Common::String &LibName, const lua_constant_reg *Constants);
static bool addConstantsToLib(lua_State *L, const Common::String &libName, const lua_constant_reg *constants);
/**
* Adds a set of methods to a Lua class
@ -92,7 +92,7 @@ public:
* The array must be terminated with the enry (0, 0)
* @return Returns true if successful, otherwise false.
*/
static bool AddMethodsToClass(lua_State *L, const Common::String &ClassName, const luaL_reg *Methods);
static bool addMethodsToClass(lua_State *L, const Common::String &className, const luaL_reg *methods);
/**
* Sets the garbage collector callback method when items of a particular class are deleted
@ -102,25 +102,25 @@ public:
* @param GCHandler A function pointer
* @return Returns true if successful, otherwise false.
*/
static bool SetClassGCHandler(lua_State *L, const Common::String &ClassName, lua_CFunction GCHandler);
static bool setClassGCHandler(lua_State *L, const Common::String &className, lua_CFunction GCHandler);
/**
* Returns a string containing a stack dump of the Lua stack
* @param L A pointer to the Lua VM
*/
static Common::String StackDump(lua_State *L);
static Common::String stackDump(lua_State *L);
/**
* Returns a string that describes the contents of a table
* @param L A pointer to the Lua VM
* @remark The table must be on the Lua stack to be read out.
*/
static Common::String TableDump(lua_State *L);
static Common::String tableDump(lua_State *L);
static bool GetMetatable(lua_State *L, const Common::String &TableName);
static bool getMetatable(lua_State *L, const Common::String &tableName);
private:
static bool _CreateTable(lua_State *L, const Common::String &TableName);
static bool createTable(lua_State *L, const Common::String &tableName);
};
} // End of namespace Sword25

View File

@ -32,10 +32,6 @@
*
*/
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/script/luacallback.h"
#include "sword25/script/luabindhelper.h"
@ -51,30 +47,22 @@ const char *CALLBACKTABLE_NAME = "__CALLBACKS";
}
// -----------------------------------------------------------------------------
namespace Sword25 {
#define BS_LOG_PREFIX "LUA"
// -----------------------------------------------------------------------------
LuaCallback::LuaCallback(lua_State *L) {
// Create callback table
lua_newtable(L);
lua_setglobal(L, CALLBACKTABLE_NAME);
}
// -----------------------------------------------------------------------------
LuaCallback::~LuaCallback() {
}
// -----------------------------------------------------------------------------
void LuaCallback::RegisterCallbackFunction(lua_State *L, uint ObjectHandle) {
void LuaCallback::registerCallbackFunction(lua_State *L, uint objectHandle) {
BS_ASSERT(lua_isfunction(L, -1));
EnsureObjectCallbackTableExists(L, ObjectHandle);
ensureObjectCallbackTableExists(L, objectHandle);
// Store function in the callback object table store
lua_pushvalue(L, -2);
@ -84,11 +72,9 @@ void LuaCallback::RegisterCallbackFunction(lua_State *L, uint ObjectHandle) {
lua_pop(L, 2);
}
// -----------------------------------------------------------------------------
void LuaCallback::UnregisterCallbackFunction(lua_State *L, uint ObjectHandle) {
void LuaCallback::unregisterCallbackFunction(lua_State *L, uint objectHandle) {
BS_ASSERT(lua_isfunction(L, -1));
EnsureObjectCallbackTableExists(L, ObjectHandle);
ensureObjectCallbackTableExists(L, objectHandle);
// Iterate over all elements of the object callback table and remove the function from it
lua_pushnil(L);
@ -114,23 +100,19 @@ void LuaCallback::UnregisterCallbackFunction(lua_State *L, uint ObjectHandle) {
lua_pop(L, 2);
}
// -----------------------------------------------------------------------------
void LuaCallback::RemoveAllObjectCallbacks(lua_State *L, uint ObjectHandle) {
PushCallbackTable(L);
void LuaCallback::removeAllObjectCallbacks(lua_State *L, uint objectHandle) {
pushCallbackTable(L);
// Remove the object callback from the callback table
lua_pushnumber(L, ObjectHandle);
lua_pushnumber(L, objectHandle);
lua_pushnil(L);
lua_settable(L, -3);
lua_pop(L, 1);
}
// -----------------------------------------------------------------------------
void LuaCallback::InvokeCallbackFunctions(lua_State *L, uint ObjectHandle) {
EnsureObjectCallbackTableExists(L, ObjectHandle);
void LuaCallback::invokeCallbackFunctions(lua_State *L, uint objectHandle) {
ensureObjectCallbackTableExists(L, objectHandle);
// Iterate through the table and perform all the callbacks
lua_pushnil(L);
@ -142,10 +124,10 @@ void LuaCallback::InvokeCallbackFunctions(lua_State *L, uint ObjectHandle) {
// Pre-Function Call
// Derived classes can function in this parameter onto the stack.
// The return value indicates the number of parameters
int ArgumentCount = PreFunctionInvokation(L);
int argumentCount = preFunctionInvokation(L);
// Lua_pcall the function and the parameters pop themselves from the stack
if (lua_pcall(L, ArgumentCount, 0, 0) != 0) {
if (lua_pcall(L, argumentCount, 0, 0) != 0) {
// An error has occurred
BS_LOG_ERRORLN("An error occured executing a callback function: %s", lua_tostring(L, -1));
@ -159,21 +141,19 @@ void LuaCallback::InvokeCallbackFunctions(lua_State *L, uint ObjectHandle) {
}
}
// -----------------------------------------------------------------------------
void LuaCallback::EnsureObjectCallbackTableExists(lua_State *L, uint ObjectHandle) {
PushObjectCallbackTable(L, ObjectHandle);
void LuaCallback::ensureObjectCallbackTableExists(lua_State *L, uint objectHandle) {
pushObjectCallbackTable(L, objectHandle);
// If the table is nil, it must first be created
if (lua_isnil(L, -1)) {
// Pop nil from stack
lua_pop(L, 1);
PushCallbackTable(L);
pushCallbackTable(L);
// Create the table, and put the ObjectHandle into it
// Create the table, and put the objectHandle into it
lua_newtable(L);
lua_pushnumber(L, ObjectHandle);
lua_pushnumber(L, objectHandle);
lua_pushvalue(L, -2);
lua_settable(L, -4);
@ -182,19 +162,15 @@ void LuaCallback::EnsureObjectCallbackTableExists(lua_State *L, uint ObjectHandl
}
}
// -----------------------------------------------------------------------------
void LuaCallback::PushCallbackTable(lua_State *L) {
void LuaCallback::pushCallbackTable(lua_State *L) {
lua_getglobal(L, CALLBACKTABLE_NAME);
}
// -----------------------------------------------------------------------------
void LuaCallback::PushObjectCallbackTable(lua_State *L, uint ObjectHandle) {
PushCallbackTable(L);
void LuaCallback::pushObjectCallbackTable(lua_State *L, uint objectHandle) {
pushCallbackTable(L);
// Push Object Callback table onto the stack
lua_pushnumber(L, ObjectHandle);
lua_pushnumber(L, objectHandle);
lua_gettable(L, -2);
// Pop the callback table from the stack

View File

@ -35,16 +35,8 @@
#ifndef SWORD25_LUACALLBACK_H
#define SWORD25_LUACALLBACK_H
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "sword25/kernel/common.h"
// -----------------------------------------------------------------------------
// Forward Declarations
// -----------------------------------------------------------------------------
namespace Lua {
struct lua_State;
@ -55,34 +47,30 @@ using namespace Lua;
namespace Sword25 {
// -----------------------------------------------------------------------------
// Class definitions
// -----------------------------------------------------------------------------
class LuaCallback {
public:
LuaCallback(lua_State *L);
virtual ~LuaCallback();
// Funktion muss auf dem Lua-Stack liegen.
void RegisterCallbackFunction(lua_State *L, uint ObjectHandle);
void registerCallbackFunction(lua_State *L, uint objectHandle);
// Funktion muss auf dem Lua-Stack liegen.
void UnregisterCallbackFunction(lua_State *L, uint ObjectHandle);
void unregisterCallbackFunction(lua_State *L, uint objectHandle);
void RemoveAllObjectCallbacks(lua_State *L, uint ObjectHandle);
void removeAllObjectCallbacks(lua_State *L, uint objectHandle);
void InvokeCallbackFunctions(lua_State *L, uint ObjectHandle);
void invokeCallbackFunctions(lua_State *L, uint objectHandle);
protected:
virtual int PreFunctionInvokation(lua_State *L) {
virtual int preFunctionInvokation(lua_State *L) {
return 0;
}
private:
void EnsureObjectCallbackTableExists(lua_State *L, uint ObjectHandle);
void PushCallbackTable(lua_State *L);
void PushObjectCallbackTable(lua_State *L, uint ObjectHandle);
void ensureObjectCallbackTableExists(lua_State *L, uint objectHandle);
void pushCallbackTable(lua_State *L);
void pushObjectCallbackTable(lua_State *L, uint objectHandle);
};
} // End of namespace Sword25

View File

@ -34,10 +34,6 @@
#define BS_LOG_PREFIX "LUA"
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "common/array.h"
#include "common/debug-channels.h"
@ -64,34 +60,24 @@ namespace Sword25 {
using namespace Lua;
// -----------------------------------------------------------------------------
// Constructor / Destructor
// -----------------------------------------------------------------------------
LuaScriptEngine::LuaScriptEngine(Kernel *KernelPtr) :
ScriptEngine(KernelPtr),
m_State(0),
m_PcallErrorhandlerRegistryIndex(0) {
_state(0),
_pcallErrorhandlerRegistryIndex(0) {
}
// -----------------------------------------------------------------------------
LuaScriptEngine::~LuaScriptEngine() {
// Lua de-initialisation
if (m_State)
lua_close(m_State);
if (_state)
lua_close(_state);
}
// -----------------------------------------------------------------------------
Service *LuaScriptEngine_CreateObject(Kernel *KernelPtr) {
return new LuaScriptEngine(KernelPtr);
}
// -----------------------------------------------------------------------------
namespace {
int PanicCB(lua_State *L) {
int panicCB(lua_State *L) {
BS_LOG_ERRORLN("Lua panic. Error message: %s", lua_isnil(L, -1) ? "" : lua_tostring(L, -1));
return 0;
}
@ -104,50 +90,48 @@ void debugHook(lua_State *L, lua_Debug *ar) {
}
}
// -----------------------------------------------------------------------------
bool LuaScriptEngine::Init() {
bool LuaScriptEngine::init() {
// Lua-State initialisation, as well as standard libaries initialisation
m_State = luaL_newstate();
if (!m_State || ! RegisterStandardLibs() || !RegisterStandardLibExtensions()) {
_state = luaL_newstate();
if (!_state || ! registerStandardLibs() || !registerStandardLibExtensions()) {
BS_LOG_ERRORLN("Lua could not be initialized.");
return false;
}
// Register panic callback function
lua_atpanic(m_State, PanicCB);
lua_atpanic(_state, panicCB);
// Error handler for lua_pcall calls
// The code below contains a local error handler function
const char ErrorHandlerCode[] =
const char errorHandlerCode[] =
"local function ErrorHandler(message) "
" return message .. '\\n' .. debug.traceback('', 2) "
"end "
"return ErrorHandler";
// Compile the code
if (luaL_loadbuffer(m_State, ErrorHandlerCode, strlen(ErrorHandlerCode), "PCALL ERRORHANDLER") != 0) {
if (luaL_loadbuffer(_state, errorHandlerCode, strlen(errorHandlerCode), "PCALL ERRORHANDLER") != 0) {
// An error occurred, so dislay the reason and exit
BS_LOG_ERRORLN("Couldn't compile luaL_pcall errorhandler:\n%s", lua_tostring(m_State, -1));
lua_pop(m_State, 1);
BS_LOG_ERRORLN("Couldn't compile luaL_pcall errorhandler:\n%s", lua_tostring(_state, -1));
lua_pop(_state, 1);
return false;
}
// Running the code, the error handler function sets the top of the stack
if (lua_pcall(m_State, 0, 1, 0) != 0) {
if (lua_pcall(_state, 0, 1, 0) != 0) {
// An error occurred, so dislay the reason and exit
BS_LOG_ERRORLN("Couldn't prepare luaL_pcall errorhandler:\n%s", lua_tostring(m_State, -1));
lua_pop(m_State, 1);
BS_LOG_ERRORLN("Couldn't prepare luaL_pcall errorhandler:\n%s", lua_tostring(_state, -1));
lua_pop(_state, 1);
return false;
}
// Place the error handler function in the Lua registry, and remember the index
m_PcallErrorhandlerRegistryIndex = luaL_ref(m_State, LUA_REGISTRYINDEX);
_pcallErrorhandlerRegistryIndex = luaL_ref(_state, LUA_REGISTRYINDEX);
// Initialise the Pluto-Persistence library
luaopen_pluto(m_State);
lua_pop(m_State, 1);
luaopen_pluto(_state);
lua_pop(_state, 1);
// Initialize debugging callback
if (DebugMan.isDebugChannelEnabled(kDebugScript)) {
@ -160,7 +144,7 @@ bool LuaScriptEngine::Init() {
mask |= LUA_MASKLINE;
if (mask != 0)
lua_sethook(m_State, debugHook, mask, 0);
lua_sethook(_state, debugHook, mask, 0);
}
BS_LOGLN("Lua initialized.");
@ -168,134 +152,118 @@ bool LuaScriptEngine::Init() {
return true;
}
// -----------------------------------------------------------------------------
bool LuaScriptEngine::ExecuteFile(const Common::String &FileName) {
bool LuaScriptEngine::executeFile(const Common::String &fileName) {
#ifdef DEBUG
int __startStackDepth = lua_gettop(m_State);
int __startStackDepth = lua_gettop(_state);
#endif
debug(2, "ExecuteFile(%s)", FileName.c_str());
debug(2, "LuaScriptEngine::executeFile(%s)", fileName.c_str());
// Get a pointer to the package manager
PackageManager *pPackage = static_cast<PackageManager *>(Kernel::GetInstance()->GetService("package"));
BS_ASSERT(pPackage);
// File read
uint FileSize;
byte *FileData = pPackage->getFile(FileName, &FileSize);
if (!FileData) {
BS_LOG_ERRORLN("Couldn't read \"%s\".", FileName.c_str());
uint fileSize;
byte *fileData = pPackage->getFile(fileName, &fileSize);
if (!fileData) {
BS_LOG_ERRORLN("Couldn't read \"%s\".", fileName.c_str());
#ifdef DEBUG
BS_ASSERT(__startStackDepth == lua_gettop(m_State));
BS_ASSERT(__startStackDepth == lua_gettop(_state));
#endif
return false;
}
// Run the file content
if (!ExecuteBuffer(FileData, FileSize, "@" + pPackage->getAbsolutePath(FileName))) {
if (!executeBuffer(fileData, fileSize, "@" + pPackage->getAbsolutePath(fileName))) {
// Release file buffer
delete[] FileData;
delete[] fileData;
#ifdef DEBUG
BS_ASSERT(__startStackDepth == lua_gettop(m_State));
BS_ASSERT(__startStackDepth == lua_gettop(_state));
#endif
return false;
}
// Release file buffer
delete[] FileData;
delete[] fileData;
#ifdef DEBUG
BS_ASSERT(__startStackDepth == lua_gettop(m_State));
BS_ASSERT(__startStackDepth == lua_gettop(_state));
#endif
return true;
}
// -----------------------------------------------------------------------------
bool LuaScriptEngine::ExecuteString(const Common::String &Code) {
return ExecuteBuffer((byte *)Code.c_str(), Code.size(), "???");
bool LuaScriptEngine::executeString(const Common::String &code) {
return executeBuffer((byte *)code.c_str(), code.size(), "???");
}
// -----------------------------------------------------------------------------
namespace {
void RemoveForbiddenFunctions(lua_State *L) {
void removeForbiddenFunctions(lua_State *L) {
static const char *FORBIDDEN_FUNCTIONS[] = {
"dofile",
0
};
const char **Iterator = FORBIDDEN_FUNCTIONS;
while (*Iterator) {
const char **iterator = FORBIDDEN_FUNCTIONS;
while (*iterator) {
lua_pushnil(L);
lua_setfield(L, LUA_GLOBALSINDEX, *Iterator);
++Iterator;
lua_setfield(L, LUA_GLOBALSINDEX, *iterator);
++iterator;
}
}
}
bool LuaScriptEngine::RegisterStandardLibs() {
luaL_openlibs(m_State);
RemoveForbiddenFunctions(m_State);
bool LuaScriptEngine::registerStandardLibs() {
luaL_openlibs(_state);
removeForbiddenFunctions(_state);
return true;
}
// -----------------------------------------------------------------------------
bool LuaScriptEngine::ExecuteBuffer(const byte *Data, uint Size, const Common::String &Name) const {
bool LuaScriptEngine::executeBuffer(const byte *data, uint size, const Common::String &name) const {
// Compile buffer
if (luaL_loadbuffer(m_State, (const char *)Data, Size, Name.c_str()) != 0) {
BS_LOG_ERRORLN("Couldn't compile \"%s\":\n%s", Name.c_str(), lua_tostring(m_State, -1));
lua_pop(m_State, 1);
if (luaL_loadbuffer(_state, (const char *)data, size, name.c_str()) != 0) {
BS_LOG_ERRORLN("Couldn't compile \"%s\":\n%s", name.c_str(), lua_tostring(_state, -1));
lua_pop(_state, 1);
return false;
}
// Error handling function to be executed after the function is put on the stack
lua_rawgeti(m_State, LUA_REGISTRYINDEX, m_PcallErrorhandlerRegistryIndex);
lua_insert(m_State, -2);
lua_rawgeti(_state, LUA_REGISTRYINDEX, _pcallErrorhandlerRegistryIndex);
lua_insert(_state, -2);
// Run buffer contents
if (lua_pcall(m_State, 0, 0, -2) != 0) {
if (lua_pcall(_state, 0, 0, -2) != 0) {
BS_LOG_ERRORLN("An error occured while executing \"%s\":\n%s.",
Name.c_str(),
lua_tostring(m_State, -1));
lua_pop(m_State, 2);
name.c_str(),
lua_tostring(_state, -1));
lua_pop(_state, 2);
return false;
}
// Remove the error handler function from the stack
lua_pop(m_State, 1);
lua_pop(_state, 1);
return true;
}
// -----------------------------------------------------------------------------
void LuaScriptEngine::setCommandLine(const Common::StringArray &commandLineParameters) {
lua_newtable(_state);
void LuaScriptEngine::SetCommandLine(const Common::StringArray &CommandLineParameters) {
debug(0, "SetCommandLine()");
lua_newtable(m_State);
for (size_t i = 0; i < CommandLineParameters.size(); ++i) {
lua_pushnumber(m_State, i + 1);
lua_pushstring(m_State, CommandLineParameters[i].c_str());
lua_settable(m_State, -3);
for (size_t i = 0; i < commandLineParameters.size(); ++i) {
lua_pushnumber(_state, i + 1);
lua_pushstring(_state, commandLineParameters[i].c_str());
lua_settable(_state, -3);
}
lua_setglobal(m_State, "CommandLine");
lua_setglobal(_state, "CommandLine");
}
// -----------------------------------------------------------------------------
namespace {
const char *PERMANENTS_TABLE_NAME = "Permanents";
// -------------------------------------------------------------------------
// This array contains the name of global Lua objects that should not be persisted
const char *STANDARD_PERMANENTS[] = {
"string",
@ -347,16 +315,12 @@ const char *STANDARD_PERMANENTS[] = {
0
};
// -------------------------------------------------------------------------
enum PERMANENT_TABLE_TYPE {
PTT_PERSIST,
PTT_UNPERSIST
};
// -------------------------------------------------------------------------
bool PushPermanentsTable(lua_State *L, PERMANENT_TABLE_TYPE TableType) {
bool pushPermanentsTable(lua_State *L, PERMANENT_TABLE_TYPE tableType) {
// Permanents-Table
lua_newtable(L);
@ -371,7 +335,8 @@ bool PushPermanentsTable(lua_State *L, PERMANENT_TABLE_TYPE TableType) {
// If it is loaded, then it can be used
// In this case, the position of name and object are reversed on the stack
if (TableType == PTT_UNPERSIST) lua_insert(L, -2);
if (tableType == PTT_UNPERSIST)
lua_insert(L, -2);
// Make an entry in the table
lua_settable(L, -3);
@ -400,7 +365,8 @@ bool PushPermanentsTable(lua_State *L, PERMANENT_TABLE_TYPE TableType) {
// If it is loaded, then it can be used
// In this case, the position of name and object are reversed on the stack
if (TableType == PTT_UNPERSIST) lua_insert(L, -2);
if (tableType == PTT_UNPERSIST)
lua_insert(L, -2);
// Make an entry in the results table
lua_settable(L, -6);
@ -424,7 +390,8 @@ bool PushPermanentsTable(lua_State *L, PERMANENT_TABLE_TYPE TableType) {
// Store coroutine.yield with it's own unique value in the Permanents table
lua_pushstring(L, "coroutine.yield");
if (TableType == PTT_UNPERSIST) lua_insert(L, -2);
if (tableType == PTT_UNPERSIST)
lua_insert(L, -2);
lua_settable(L, -4);
@ -435,48 +402,44 @@ bool PushPermanentsTable(lua_State *L, PERMANENT_TABLE_TYPE TableType) {
}
}
// -----------------------------------------------------------------------------
namespace {
int Chunkwriter(lua_State *L, const void *p, size_t sz, void *ud) {
int chunkwriter(lua_State *L, const void *p, size_t sz, void *ud) {
Common::Array<byte> & chunkData = *reinterpret_cast<Common::Array<byte> * >(ud);
const byte *buffer = reinterpret_cast<const byte *>(p);
while (sz--) chunkData.push_back(*buffer++) ;
while (sz--)
chunkData.push_back(*buffer++);
return 1;
}
}
bool LuaScriptEngine::persist(OutputPersistenceBlock &Writer) {
bool LuaScriptEngine::persist(OutputPersistenceBlock &writer) {
// Empty the Lua stack. pluto_persist() xepects that the stack is empty except for its parameters
lua_settop(m_State, 0);
lua_settop(_state, 0);
// Garbage Collection erzwingen.
lua_gc(m_State, LUA_GCCOLLECT, 0);
lua_gc(_state, LUA_GCCOLLECT, 0);
// Permanents-Table is set on the stack
// pluto_persist expects these two items on the Lua stack
PushPermanentsTable(m_State, PTT_PERSIST);
lua_getglobal(m_State, "_G");
pushPermanentsTable(_state, PTT_PERSIST);
lua_getglobal(_state, "_G");
// Lua persists and stores the data in a Common::Array
Common::Array<byte> chunkData;
pluto_persist(m_State, Chunkwriter, &chunkData);
pluto_persist(_state, chunkwriter, &chunkData);
// Persistenzdaten in den Writer schreiben.
Writer.write(&chunkData[0], chunkData.size());
writer.write(&chunkData[0], chunkData.size());
// Die beiden Tabellen vom Stack nehmen.
lua_pop(m_State, 2);
lua_pop(_state, 2);
return true;
}
// -----------------------------------------------------------------------------
namespace {
// -------------------------------------------------------------------------
struct ChunkreaderData {
void *BufferPtr;
@ -484,9 +447,7 @@ struct ChunkreaderData {
bool BufferReturned;
};
// ------------------------------------------------------------------------
const char *Chunkreader(lua_State *L, void *ud, size_t *sz) {
const char *chunkreader(lua_State *L, void *ud, size_t *sz) {
ChunkreaderData &cd = *reinterpret_cast<ChunkreaderData *>(ud);
if (!cd.BufferReturned) {
@ -498,9 +459,7 @@ const char *Chunkreader(lua_State *L, void *ud, size_t *sz) {
}
}
// -------------------------------------------------------------------------
void ClearGlobalTable(lua_State *L, const char **Exceptions) {
void clearGlobalTable(lua_State *L, const char **exceptions) {
// Iterate over all elements of the global table
lua_pushvalue(L, LUA_GLOBALSINDEX);
lua_pushnil(L);
@ -512,18 +471,19 @@ void ClearGlobalTable(lua_State *L, const char **Exceptions) {
// Determine whether the item is set to nil, so you want to remove from the global table.
// For this will determine whether the element name is a string and is present in
// the list of exceptions
bool SetElementToNil = true;
bool setElementToNil = true;
if (lua_isstring(L, -1)) {
const char *IndexString = lua_tostring(L, -1);
const char **ExceptionsWalker = Exceptions;
while (*ExceptionsWalker) {
if (strcmp(IndexString, *ExceptionsWalker) == 0) SetElementToNil = false;
++ExceptionsWalker;
const char *indexString = lua_tostring(L, -1);
const char **exceptionsWalker = exceptions;
while (*exceptionsWalker) {
if (strcmp(indexString, *exceptionsWalker) == 0)
setElementToNil = false;
++exceptionsWalker;
}
}
// If the above test showed that the item should be removed, it is removed by setting the value to nil.
if (SetElementToNil) {
if (setElementToNil) {
lua_pushvalue(L, -1);
lua_pushnil(L);
lua_settable(L, LUA_GLOBALSINDEX);
@ -538,39 +498,37 @@ void ClearGlobalTable(lua_State *L, const char **Exceptions) {
}
}
// -----------------------------------------------------------------------------
bool LuaScriptEngine::unpersist(InputPersistenceBlock &Reader) {
bool LuaScriptEngine::unpersist(InputPersistenceBlock &reader) {
// Empty the Lua stack. pluto_persist() xepects that the stack is empty except for its parameters
lua_settop(m_State, 0);
lua_settop(_state, 0);
// Permanents table is placed on the stack. This has already happened at this point, because
// to create the table all permanents must be accessible. This is the case only for the
// beginning of the function, because the global table is emptied below
PushPermanentsTable(m_State, PTT_UNPERSIST);
pushPermanentsTable(_state, PTT_UNPERSIST);
// All items from global table of _G and __METATABLES are removed.
// After a garbage collection is performed, and thus all managed objects deleted
// __METATABLES is not immediately removed becausen the Metatables are needed
// for the finalisers of objects.
static const char *ClearExceptionsFirstPass[] = {
static const char *clearExceptionsFirstPass[] = {
"_G",
"__METATABLES",
0
};
ClearGlobalTable(m_State, ClearExceptionsFirstPass);
clearGlobalTable(_state, clearExceptionsFirstPass);
// In the second pass, the Metatables are removed
static const char *ClearExceptionsSecondPass[] = {
static const char *clearExceptionsSecondPass[] = {
"_G",
0
};
ClearGlobalTable(m_State, ClearExceptionsSecondPass);
clearGlobalTable(_state, clearExceptionsSecondPass);
// Persisted Lua data
Common::Array<byte> chunkData;
Reader.read(chunkData);
reader.read(chunkData);
// Chunk-Reader initialisation. It is used with pluto_unpersist to restore read data
ChunkreaderData cd;
@ -578,32 +536,32 @@ bool LuaScriptEngine::unpersist(InputPersistenceBlock &Reader) {
cd.Size = chunkData.size();
cd.BufferReturned = false;
pluto_unpersist(m_State, Chunkreader, &cd);
pluto_unpersist(_state, chunkreader, &cd);
// Permanents-Table is removed from stack
lua_remove(m_State, -2);
lua_remove(_state, -2);
// The read elements in the global table about
lua_pushnil(m_State);
while (lua_next(m_State, -2) != 0) {
lua_pushnil(_state);
while (lua_next(_state, -2) != 0) {
// The referenec to the global table (_G) must not be overwritten, or ticks from Lua total
bool IsGlobalReference = lua_isstring(m_State, -2) && strcmp(lua_tostring(m_State, -2), "_G") == 0;
if (!IsGlobalReference) {
lua_pushvalue(m_State, -2);
lua_pushvalue(m_State, -2);
bool isGlobalReference = lua_isstring(_state, -2) && strcmp(lua_tostring(_state, -2), "_G") == 0;
if (!isGlobalReference) {
lua_pushvalue(_state, -2);
lua_pushvalue(_state, -2);
lua_settable(m_State, LUA_GLOBALSINDEX);
lua_settable(_state, LUA_GLOBALSINDEX);
}
// Pop value from the stack. The index is then ready for the next call to lua_next()
lua_pop(m_State, 1);
lua_pop(_state, 1);
}
// The table with the loaded data is popped from the stack
lua_pop(m_State, 1);
lua_pop(_state, 1);
// Force garbage collection
lua_gc(m_State, LUA_GCCOLLECT, 0);
lua_gc(_state, LUA_GCCOLLECT, 0);
return true;
}

View File

@ -35,19 +35,11 @@
#ifndef SWORD25_LUASCRIPT_H
#define SWORD25_LUASCRIPT_H
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "common/str.h"
#include "common/str-array.h"
#include "sword25/kernel/common.h"
#include "sword25/script/script.h"
// -----------------------------------------------------------------------------
// Forward declarations
// -----------------------------------------------------------------------------
namespace Lua {
struct lua_State;
@ -60,16 +52,8 @@ namespace Sword25 {
class Kernel;
// -----------------------------------------------------------------------------
// Class declaration
// -----------------------------------------------------------------------------
class LuaScriptEngine : public ScriptEngine {
public:
// -----------------------------------------------------------------------------
// Constructor / Destructor
// -----------------------------------------------------------------------------
LuaScriptEngine(Kernel *KernelPtr);
virtual ~LuaScriptEngine();
@ -77,28 +61,28 @@ public:
* Initialises the scripting engine
* @return Returns true if successful, otherwise false.
*/
virtual bool Init();
virtual bool init();
/**
* Loads a script file and executes it
* @param FileName The filename of the script
* @return Returns true if successful, otherwise false.
*/
virtual bool ExecuteFile(const Common::String &FileName);
virtual bool executeFile(const Common::String &fileName);
/**
* Execute a string of script code
* @param Code A string of script code
* @return Returns true if successful, otherwise false.
*/
virtual bool ExecuteString(const Common::String &Code);
virtual bool executeString(const Common::String &code);
/**
* Returns a pointer to the main object of the scripting language
* @remark Using this method breaks the encapsulation of the language
*/
virtual void *GetScriptObject() {
return m_State;
virtual void *getScriptObject() {
return _state;
}
/**
@ -107,7 +91,7 @@ public:
* @remark How the command line parameters will be used by scripts is
* dependant on the particular implementation.
*/
virtual void SetCommandLine(const Common::StringArray &CommandLineParameters);
virtual void setCommandLine(const Common::StringArray &commandLineParameters);
/**
* @remark The Lua stack is cleared by this method
@ -119,12 +103,12 @@ public:
virtual bool unpersist(InputPersistenceBlock &reader);
private:
lua_State *m_State;
int m_PcallErrorhandlerRegistryIndex;
lua_State *_state;
int _pcallErrorhandlerRegistryIndex;
bool RegisterStandardLibs();
bool RegisterStandardLibExtensions();
bool ExecuteBuffer(const byte *Data, uint Size, const Common::String &Name) const;
bool registerStandardLibs();
bool registerStandardLibExtensions();
bool executeBuffer(const byte *data, uint size, const Common::String &name) const;
};
} // End of namespace Sword25

View File

@ -35,10 +35,6 @@
#ifndef SWORD25_SCRIPT_H
#define SWORD25_SCRIPT_H
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include "common/array.h"
#include "common/str.h"
#include "sword25/kernel/common.h"
@ -47,24 +43,12 @@
namespace Sword25 {
// -----------------------------------------------------------------------------
// Forward declarations
// -----------------------------------------------------------------------------
class Kernel;
class OutputPersistenceBlock;
class BS_InputPersistenceBlock;
// -----------------------------------------------------------------------------
// Class declaration
// -----------------------------------------------------------------------------
class ScriptEngine : public Service, public Persistable {
public:
// -----------------------------------------------------------------------------
// Constructor / destructor
// -----------------------------------------------------------------------------
ScriptEngine(Kernel *KernelPtr) : Service(KernelPtr) {};
virtual ~ScriptEngine() {};
@ -75,25 +59,25 @@ public:
/**
* Initialises the scrip tengine. Returns true if successful, false otherwise.
*/
virtual bool Init() = 0;
virtual bool init() = 0;
/**
* Loads a script file and executes it.
* @param FileName The script filename
*/
virtual bool ExecuteFile(const Common::String &FileName) = 0;
virtual bool executeFile(const Common::String &fileName) = 0;
/**
* Executes a specified script fragment
* @param Code String of script code
*/
virtual bool ExecuteString(const Common::String &Code) = 0;
virtual bool executeString(const Common::String &code) = 0;
/**
* Returns a pointer to the main object of the script engine
* Note: Using this method breaks the encapsulation of the language from the rest of the engine.
*/
virtual void *GetScriptObject() = 0;
virtual void *getScriptObject() = 0;
/**
* Makes the command line parameters for the script environment available
@ -101,7 +85,7 @@ public:
* particular implementation.
* @param CommandLineParameters List containing the command line parameters
*/
virtual void SetCommandLine(const Common::Array<Common::String> &CommandLineParameters) = 0;
virtual void setCommandLine(const Common::Array<Common::String> &commandLineParameters) = 0;
virtual bool persist(OutputPersistenceBlock &writer) = 0;
virtual bool unpersist(InputPersistenceBlock &reader) = 0;

View File

@ -353,11 +353,11 @@ bool SoundEngine::registerScriptBindings() {
BS_ASSERT(pKernel);
ScriptEngine *pScript = static_cast<ScriptEngine *>(pKernel->GetService("script"));
BS_ASSERT(pScript);
lua_State *L = static_cast<lua_State *>(pScript->GetScriptObject());
lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
BS_ASSERT(L);
if (!LuaBindhelper::AddFunctionsToLib(L, SFX_LIBRARY_NAME, SFX_FUNCTIONS)) return false;
if (!LuaBindhelper::AddConstantsToLib(L, SFX_LIBRARY_NAME, SFX_CONSTANTS)) return false;
if (!LuaBindhelper::addFunctionsToLib(L, SFX_LIBRARY_NAME, SFX_FUNCTIONS)) return false;
if (!LuaBindhelper::addConstantsToLib(L, SFX_LIBRARY_NAME, SFX_CONSTANTS)) return false;
return true;
}

View File

@ -122,7 +122,7 @@ Common::Error Sword25Engine::appStart() {
}
Common::StringArray commandParameters;
scriptPtr->SetCommandLine(commandParameters);
scriptPtr->setCommandLine(commandParameters);
return Common::kNoError;
}
@ -131,7 +131,7 @@ bool Sword25Engine::appMain() {
// The main script start. This script loads all the other scripts and starts the actual game.
ScriptEngine *scriptPtr = static_cast<ScriptEngine *>(Kernel::GetInstance()->GetService("script"));
BS_ASSERT(scriptPtr);
scriptPtr->ExecuteFile(DEFAULT_SCRIPT_FILE);
scriptPtr->executeFile(DEFAULT_SCRIPT_FILE);
return true;
}