LuaFunction LuaFunction::createFromCode(lua_State* L, std::string const& code, std::string const& name) { int err = luaL_loadbuffer(L, code.c_str(), code.length(), name.c_str()); if (!err) { LuaFunction func; func.setReference(LuaReference::create(L)); lua_pop(L, 1); return func; } else { // Get the error message size_t len; const char* err = lua_tolstring(L, -1, &len); lua_pop(L, 1); throw LuaException(std::string(err, len)); } }
TEST_F(LuaFunctionTest, SetReference) { { ScopedLuaStackTest stackTest(L); LuaFunction func = LuaFunction::createFromCode(L, "invalid()"); lua_pushliteral(L, "abc"); ASSERT_THROW(func.setReference(UniqueLuaReference::create(L)), LuaException); lua_pop(L, 1); lua_getglobal(L, "type"); ASSERT_NO_THROW(func.setReference(UniqueLuaReference::create(L))); lua_pop(L, 1); } }
LuaFunction LuaFunction::createFromCFunction(lua_State* L, lua_CFunction function) { LuaFunction func; lua_pushcfunction(L, function); func.setReference(LuaReference::create(L)); lua_pop(L, 1); return func; }
LuaFunction LuaFunction::createFromCFunction(lua_State* L, lua_CFunction function, const LuaValueList& upvalues) { LuaFunction func; for (auto& val : upvalues) { val.pushValue(); } lua_pushcclosure(L, function, (int) upvalues.size()); func.setReference(UniqueLuaReference::create(L)); lua_pop(L, 1); return func; }
bool ::luacpp::convert::popValue(lua_State* luaState, LuaFunction& target, int stackposition, bool remove) { if (!internal::isValidIndex(luaState, stackposition)) { return false; } if (!lua_isfunction(luaState, stackposition)) { return false; } else { target.setReference(UniqueLuaReference::create(luaState, stackposition)); if (remove) { lua_remove(luaState, stackposition); } return true; } }