Created
October 21, 2012 16:36
-
-
Save henkboom/3927519 to your computer and use it in GitHub Desktop.
Bootstrapping LuaJIT on Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <android/log.h> | |
#include "android_native_app_glue.h" | |
#include "lua.h" | |
#include "lualib.h" | |
#include "lauxlib.h" | |
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "beamer", __VA_ARGS__)) | |
#define LOGF(...) ((void)__android_log_print(ANDROID_LOG_FATAL, "beamer", __VA_ARGS__)) | |
static struct android_app* state = NULL; | |
const char *reader(lua_State *L, void *data, size_t *size) | |
{ | |
static char buffer[1024]; | |
*size = AAsset_read(data, buffer, 1024); | |
if(*size < 0) | |
*size = 0; | |
return buffer; | |
} | |
static int loader_lua_asset (lua_State *L) | |
{ | |
const char *filename; | |
const char *name = luaL_checkstring(L, 1); | |
luaL_gsub(L, name, ".", LUA_DIRSEP); | |
lua_pushstring(L, ".lua"); | |
lua_concat(L, 2); | |
name = lua_tostring(L, -1); | |
AAsset* asset = AAssetManager_open(state->activity->assetManager, | |
name, AASSET_MODE_BUFFER); | |
if(asset == NULL) | |
{ | |
lua_pushfstring(L, "\n\tno asset '%s'", name); | |
return 1; | |
} | |
if (lua_load(L, reader, asset, name) != 0) | |
luaL_error(L, "error loading module '%s' from asset '%s':\n\t%s", | |
lua_tostring(L, 1), name, lua_tostring(L, -1)); | |
AAsset_close(asset); | |
return 1; | |
} | |
void android_main(struct android_app* _state) | |
{ | |
// Make sure glue isn't stripped. | |
app_dummy(); | |
state = _state; | |
LOGI("opening lua"); | |
lua_State *L = lua_open(); | |
luaL_openlibs(L); | |
// register the lua loader | |
LOGI("registering loader_lua_asset in package.loaders"); | |
lua_getglobal(L, "package"); | |
lua_getfield(L, -1, "loaders"); | |
lua_pushcfunction(L, loader_lua_asset); | |
lua_rawseti(L, -2, 2); | |
lua_pop(L, 2); | |
// now we're going to load init_android.lua, printing a backtrace on errors | |
LOGI("running init_android.lua"); | |
lua_getglobal(L, "debug"); | |
lua_getfield(L, -1, "traceback"); | |
{ | |
// load init_android module | |
lua_pushcfunction(L, loader_lua_asset); | |
lua_pushstring(L, "init_android"); | |
lua_call(L, 1, 1); | |
} | |
// call it with our android_app* as a parameter | |
lua_pushlightuserdata(L, state); | |
if(lua_pcall(L, 1, 0, -3) != 0) | |
{ | |
LOGF("%s", lua_tostring(L, -1)); | |
} | |
LOGI("closing lua"); | |
lua_close(L); | |
LOGI("application done"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment