From d7f52e5c82c04a45cd042e9224fb2e6f2a75f5f1 Mon Sep 17 00:00:00 2001 From: Neo Xu Date: Tue, 20 Aug 2024 01:59:42 +0800 Subject: [PATCH] example: add example to include a lua file to C code Signed-off-by: Neo Xu --- examples/luaC.lua | 2 +- simulator/lua_in_C.c | 30 ++++++++++++------------------ simulator/ui.lua | 15 +++++++++++++++ 3 files changed, 28 insertions(+), 19 deletions(-) create mode 100644 simulator/ui.lua diff --git a/examples/luaC.lua b/examples/luaC.lua index 18627bf..e121f4a 100644 --- a/examples/luaC.lua +++ b/examples/luaC.lua @@ -1,4 +1,4 @@ --- Everything is already setup in C code, check mixed.c +-- Everything is already setup in C code, check lua_in_c.c -- This file is just to trigger the demo embed_lua_in_c() diff --git a/simulator/lua_in_C.c b/simulator/lua_in_C.c index 1918234..b12d139 100644 --- a/simulator/lua_in_C.c +++ b/simulator/lua_in_C.c @@ -9,18 +9,16 @@ #define _STRINGIZE(...) #__VA_ARGS__ #define STRINGIZE(...) _STRINGIZE(__VA_ARGS__) -static const char lua_code_string[] = STRINGIZE( - local root = lvgl.get_child_by_id("luaUIroot") - root.w = lvgl.VER_RES(), - root.h = lvgl.HOR_RES(), - - btn = Button(root, { - id = "Button in Lua", - Label { - text = "Hello, lua, C and lvgl!", - align = lvgl.ALIGN_CENTER - } - }):center() +static const char lua_code_string[] = { + /* Must start with -- */ + "--" +#include "ui.lua" +}; + +static const char button_lua_code[] = STRINGIZE( + local btn = lvgl.get_child_by_id('Button in Lua') + local label = btn:get_child(0) + label.text = 'Button clicked' ); static void button_clicked(lv_event_t *e) @@ -28,11 +26,7 @@ static void button_clicked(lv_event_t *e) (void)e; lua_State *L = lv_event_get_user_data(e); LV_LOG_USER("Button clicked"); - luaL_dostring(L, "\ - local btn = lvgl.get_child_by_id('Button in Lua')\n\ - local label = btn:get_child(0)\n\ - label.text = 'Button clicked'\n\ - "); + luaL_dostring(L, button_lua_code); } static int embed_lua_in_c(lua_State *L) @@ -40,7 +34,7 @@ static int embed_lua_in_c(lua_State *L) /* We create a root obj in C and create other UIs in lua. */ lv_obj_t *root = lv_obj_create(lv_screen_active()); luavgl_add_lobj(L, root)->lua_created = false; - lv_obj_set_id(root, lv_strdup("luaUIroot")); + lv_obj_set_id(root, "luaUIroot"); int ret = luaL_dostring(L, lua_code_string); if (ret != 0) { LV_LOG_USER("luaL_dostring error: %d", ret); diff --git a/simulator/ui.lua b/simulator/ui.lua new file mode 100644 index 0000000..c72b64d --- /dev/null +++ b/simulator/ui.lua @@ -0,0 +1,15 @@ +STRINGIZE((function() --\n + local root = lvgl.get_child_by_id("luaUIroot") + root.w = lvgl.VER_RES() + root.h = lvgl.HOR_RES() + + Button(root, { + id = "Button in Lua", + Label { + text = "Hello, lua, C and lvgl!", + align = lvgl.ALIGN_CENTER + } + }):center() + +-- Keep this comment +end)())