6#include <brenta/script.hpp>
7#include <brenta/node.hpp>
8#include <brenta/logger.hpp>
13#include <lua/lualib.h>
14#include <lua/lauxlib.h>
17using namespace brenta;
19Node* Script::current_node =
nullptr;
23 if (!this->state)
return;
25 lua_close(this->state);
26 this->state =
nullptr;
29int Script::lua_get_position(lua_State* L)
31 auto* node = Script::current_node;
32 if (!node)
goto error;
34 lua_pushnumber(L, node->transform.position.x);
35 lua_pushnumber(L, node->transform.position.y);
36 lua_pushnumber(L, node->transform.position.z);
46int Script::lua_set_position(lua_State* L)
48 auto* node = Script::current_node;
51 float x = (float)luaL_checknumber(L, 1);
52 float y = (float)luaL_checknumber(L, 2);
53 float z = (float)luaL_checknumber(L, 3);
55 node->transform.position.x = x;
56 node->transform.position.y = y;
57 node->transform.position.z = z;
63 if (this->state !=
nullptr)
return;
65 this->state = luaL_newstate();
66 luaL_openlibs(this->state);
70 if (!luaL_dofile(this->state, this->path->string().c_str()) == LUA_OK)
72 ERROR(
"Script: error running script {}: {}",
73 path->string(), lua_tostring(this->state, -1));
76 else if (this->source)
78 if (!luaL_dostring(this->state, this->source->c_str()) == LUA_OK)
80 ERROR(
"Script: error running script: {}",
81 lua_tostring(this->state, -1));
86 ERROR(
"Script: tried to run script with no source");
91 lua_pushcfunction(this->state, lua_get_position);
92 lua_setglobal(this->state,
"get_position");
93 lua_pushcfunction(this->state, lua_set_position);
94 lua_setglobal(this->state,
"set_position");
96 DEBUG(
"Script: initialized");
101 if (this->state !=
nullptr)
103 lua_close(this->state);
104 this->state =
nullptr;
108 DEBUG(
"Script: reloaded");
111void Script::update(
float delta_time)
113 lua_getglobal(this->state,
"update");
114 if (!lua_isfunction(this->state, -1))
116 lua_pop(this->state, 1);
120 lua_pushnumber(this->state, delta_time);
122 if (lua_pcall(this->state, 1, 0, 0) != LUA_OK)
124 ERROR(
"Lua: Error: {}", lua_tostring(this->state, -1));
125 lua_pop(this->state, 1);