summaryrefslogtreecommitdiff
path: root/examples/scripting/lua/lua.zc
diff options
context:
space:
mode:
authorSteven <burnett@posteo.de>2026-01-17 21:22:52 +0000
committerSteven <burnett@posteo.de>2026-01-17 21:22:52 +0000
commit68d493c5f261a99b40d90e2cc4f08b24d1975234 (patch)
treee9a0e4438d1b7c8e5bb5e26ec2585918e85f8e80 /examples/scripting/lua/lua.zc
parent7ac5be7ba8f700f69009c5e980ee7b12b0653586 (diff)
chore(examples): New example for LUA bindings
Diffstat (limited to 'examples/scripting/lua/lua.zc')
-rw-r--r--examples/scripting/lua/lua.zc48
1 files changed, 48 insertions, 0 deletions
diff --git a/examples/scripting/lua/lua.zc b/examples/scripting/lua/lua.zc
new file mode 100644
index 0000000..74403bb
--- /dev/null
+++ b/examples/scripting/lua/lua.zc
@@ -0,0 +1,48 @@
+//> include: ./lua
+//> lib: ./lua
+//> link: -Wl,-Bstatic -llua54 -Wl,-Bdynamic -lm -ldl
+//> cflags: -Ofast
+
+import "lua.h";
+import "lauxlib.h";
+import "lualib.h";
+
+fn l_zenc_hello(L: lua_State*) -> int {
+ const name: string = (string)luaL_optstring(L, 1, "world");
+ println "hello from Zen-C, {name}"
+ return 0;
+}
+
+fn main() {
+ var L: lua_State* = luaL_newstate();
+
+ if (!L) return !"Could not initialize LUA.";
+
+ // Opens standard libs
+ luaL_openlibs(L);
+ defer lua_close(L);
+
+ // Expose a Zen-C function to Lua as global "zenc_hello"
+ lua_pushcfunction(L, l_zenc_hello);
+ lua_setglobal(L, "zenc_hello");
+
+ // Run some Lua from a Zen-C variable
+ const script = "print('hello from lua')\nzenc_hello('test')\n";
+
+ if (luaL_dostring(L, script) != LUA_OK) {
+ const err: string = (string)lua_tostring(L, -1);
+ !"lua error: {err}"
+ lua_pop(L, 1);
+ }
+
+ // Run some Lua from a script file
+ if (luaL_loadfile(L, "script.lua") != LUA_OK) {
+ const err: string = (string)lua_tostring(L, -1);
+ !"lua load-error: {err}"
+ lua_pop(L, 1);
+ } else if (lua_pcall(L, 0, 0, 0) != LUA_OK) {
+ const err: string = (string)lua_tostring(L, -1);
+ !"lua error: {err}"
+ lua_pop(L, 1);
+ }
+}