summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--hello.c49
-rw-r--r--hello.lua1
2 files changed, 49 insertions, 1 deletions
diff --git a/hello.c b/hello.c
index 2d719e1..8e3f2c4 100644
--- a/hello.c
+++ b/hello.c
@@ -1,6 +1,53 @@
#include <stdio.h>
+/* lua.h provides core functions, these include everything starting lua_ */
+#include <lua.h>
+/* lauxlib.h provides convenience functions, these start luaL_ */
+#include <lauxlib.h>
+
int main(void){
- printf("Hello World!\n");
+ /* The lua_State structure encapsulates your lua runtime environment
+ luaL_newstate allocates and initializes it.
+ There also exists a lua_newstate, which takes parameters for a custom
+ memory allocator, since the lua runtime needs to allocate memory.
+ luaL_newstate is a wrapper, which uses the standard C library's realloc,
+ and aborts on allocation failure.
+ */
+ lua_State *L = luaL_newstate();
+ if (!L) {
+ perror("Creating lua state");
+ return 1;
+ }
+
+ /* The following executes the file hello.lua, which returns the string
+ intended to be printed.
+ Likewise it is an auxiliary function, which reads a file,
+ compiles the contents into a function, then calls it.
+ */
+ if (luaL_dofile(L, "hello.lua")) {
+ /* dofile returns a string on the lua stack in the case of error
+ which says what went wrong, a pointer to it is retrieved with
+ lua_tostring, this exists inside the lua_State structure, so
+ if you need it after the next call to lua you have to copy it
+ */
+ char const *errmsg = lua_tostring(L, 1);
+ fprintf(stderr, "Failed to execute hello.lua: %s\n", errmsg);
+ return 2;
+ }
+
+ /* A file can take parameters and return values like a function.
+ The result is passed to printf, so IO is done outside of lua.
+ */
+ char const *result = lua_tostring(L, 1);
+ if (!result) {
+ fprintf(stderr, "hello.lua did not return a string\n");
+ return 3;
+ }
+ printf("%s\n", result);
+
+ /* lua_close frees up any resources used by the lua runtime
+ This is not necessary here, since the program is about to exit.
+ */
+ lua_close(L);
return 0;
}
diff --git a/hello.lua b/hello.lua
new file mode 100644
index 0000000..cfcbc24
--- /dev/null
+++ b/hello.lua
@@ -0,0 +1 @@
+return "Hello World!"