Skip to content

Instantly share code, notes, and snippets.

@nramsbottom
Created April 24, 2017 22:14
Show Gist options
  • Select an option

  • Save nramsbottom/4e4d8a907873fa4d1f5728832ee32851 to your computer and use it in GitHub Desktop.

Select an option

Save nramsbottom/4e4d8a907873fa4d1f5728832ee32851 to your computer and use it in GitHub Desktop.
function boo()
print "boo"
end
function add(x, y)
return x + y
end
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#pragma comment(lib, "lua53")
struct {
char name[20];
int hp;
int x;
int y;
} player;
int player_get_info(lua_State *L) {
lua_pushinteger(L, player.hp);
lua_pushinteger(L, player.x);
lua_pushinteger(L, player.y);
lua_pushlstring(L, player.name, 20);
return 4;
}
void scripting_start(lua_State **state) {
*state = luaL_newstate();
luaL_openlibs(*state);
lua_register(*state, "player_get_info", player_get_info);
}
void scripting_stop(lua_State *state) {
lua_close(state);
}
int scripting_runfile(lua_State *state, const char *filename) {
int status = luaL_loadfile(state, filename);
if (status) {
fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(state, -1));
return 1;
}
int result = lua_pcall(state, 0, LUA_MULTRET, 0);
if (result) {
fprintf(stderr, "Failed to run script: %s\n", lua_tostring(state, -1));
return 1;
}
return 0;
}
// load a script from a string
int scripting_runscript(lua_State *state, const char *name, const char *script, size_t len) {
int status = luaL_loadbuffer(state, script, len, name);
if (status) {
fprintf(stderr, "Couldn't load script: %s\n", lua_tostring(state, -1));
return 1;
}
int result = lua_pcall(state, 0, LUA_MULTRET, 0);
if (result) {
fprintf(stderr, "Failed to run script: %s\n", lua_tostring(state, -1));
return 1;
}
return 0;
}
int add(lua_State *state, int x, int y)
{
lua_pushinteger(state, x);
lua_pushinteger(state, y);
lua_call(state, "add", 2); /* call Lua function */
//strcpy(s, lua_getstring(lua_getresult(1))); /* copy result back to 's' */
}
int main(int argc, char *argv[]) {
player.x = 10;
player.y = 20;
player.hp = 100;
strcpy(player.name, "Player");
lua_State *state;
scripting_start(&state);
// load a script from disk
scripting_runfile(state, "scripts/library.lua");
// load a script from memory
const char inline_script[] = "print \"hello from inline script\"";
scripting_runscript(state, "inline.lua", inline_script, strlen(inline_script));
scripting_runfile(state, "scripts/test.lua");
scripting_stop(state);
return 0;
}
print "hello"
x, y, hp, name = player_get_info()
print (name)
boo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment