-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlua_interop.c
More file actions
36 lines (28 loc) · 893 Bytes
/
lua_interop.c
File metadata and controls
36 lines (28 loc) · 893 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <lauxlib.h>
#include <lualib.h>
#include <emscripten/emscripten.h>
const char* SCRIPT_TEMPLATE = "return require('runner').run([=====[ %s ]=====])";
const char* copyString(const char* toCopy) {
char* newstr = (char*) malloc(strlen(toCopy) + 1);
if (newstr) {
strcpy(newstr, toCopy);
}
return newstr;
}
EMSCRIPTEN_KEEPALIVE
const char* runLua(const char* script) {
const int scriptLen = strlen(SCRIPT_TEMPLATE) + strlen(script);
char fullScript[scriptLen];
sprintf(fullScript, SCRIPT_TEMPLATE, script);
lua_State* lua = luaL_newstate();
luaL_openlibs(lua);
luaL_dostring(lua, fullScript);
const char* result = lua_tostring(lua, -1);
// allocate string on heap
const char* copyOfResult = copyString(result);
lua_close(lua);
return copyOfResult;
}