diff --git a/libraries/AP_Scripting/AP_Scripting.cpp b/libraries/AP_Scripting/AP_Scripting.cpp index 9d878c244c6..49a67ed630c 100644 --- a/libraries/AP_Scripting/AP_Scripting.cpp +++ b/libraries/AP_Scripting/AP_Scripting.cpp @@ -17,13 +17,15 @@ #include #include +#include "lua_bindings.h" + // ensure that we have a set of stack sizes, and enforce constraints around it // except for the minimum size, these are allowed to be defined by the build system #undef SCRIPTING_STACK_MIN_SIZE #define SCRIPTING_STACK_MIN_SIZE 2048 #if !defined(SCRIPTING_STACK_SIZE) - #define SCRIPTING_STACK_SIZE 2048 + #define SCRIPTING_STACK_SIZE 8192 #endif // !defined(SCRIPTING_STACK_SIZE) #if !defined(SCRIPTING_STACK_MAX_SIZE) @@ -74,9 +76,28 @@ bool AP_Scripting::init(void) { void AP_Scripting::thread(void) { unsigned int loop = 0; + lua_State *state = luaL_newstate(); + luaL_openlibs(state); + load_lua_bindings(state); + + luaL_loadstring(state, "gcs.send_text(string.format(\"1 + 2 = %d\", 1+2))"); + while (true) { hal.scheduler->delay(1000); gcs().send_text(MAV_SEVERITY_INFO, "Scripting Loop: %u", loop++); + + const uint32_t startMem = hal.util->available_memory(); + const uint32_t loadEnd = AP_HAL::micros(); + lua_pushvalue(state, -1); + if(lua_pcall(state, 0, LUA_MULTRET, 0)) { + gcs().send_text(MAV_SEVERITY_INFO, "Lua: %s", lua_tostring(state, -1)); + hal.console->printf("Lua: %s", lua_tostring(state, -1)); + lua_pop(state, 1); + continue; + } + const uint32_t runEnd = AP_HAL::micros(); + const uint32_t endMem = hal.util->available_memory(); + gcs().send_text(MAV_SEVERITY_INFO, "Execution: %d Memory: %d", runEnd - loadEnd, startMem - endMem); } } diff --git a/libraries/AP_Scripting/lua_bindings.cpp b/libraries/AP_Scripting/lua_bindings.cpp new file mode 100644 index 00000000000..8a8f3cab5b2 --- /dev/null +++ b/libraries/AP_Scripting/lua_bindings.cpp @@ -0,0 +1,26 @@ +#include +#include + +#include "lua_bindings.h" + +int lua_gcs_send_text(lua_State *state) { + const char* str = lua_tostring(state, 1); + gcs().send_text(MAV_SEVERITY_INFO, str); + return 0; +} + +static const luaL_Reg gcs_functions[] = +{ + {"send_text", lua_gcs_send_text}, + {NULL, NULL} +}; + +void load_lua_bindings(lua_State *state) { + luaL_newlib(state, gcs_functions); + lua_setglobal(state, "gcs"); +} + +void hook(lua_State *L, lua_Debug *ar) { + gcs().send_text(MAV_SEVERITY_INFO, "got a debug hook"); + lua_error(L); +} diff --git a/libraries/AP_Scripting/lua_bindings.h b/libraries/AP_Scripting/lua_bindings.h new file mode 100644 index 00000000000..65134b83f3c --- /dev/null +++ b/libraries/AP_Scripting/lua_bindings.h @@ -0,0 +1,8 @@ +#pragma once + +#include "lua/src/lua.hpp" + +// load all known lua bindings into the state +void load_lua_bindings(lua_State *state); + +void hook(lua_State *L, lua_Debug *ar);