Skip to content

Instantly share code, notes, and snippets.

@daiakushi
Created January 21, 2016 14:20
Show Gist options
  • Save daiakushi/44cfa5144759ff94924f to your computer and use it in GitHub Desktop.
Save daiakushi/44cfa5144759ff94924f to your computer and use it in GitHub Desktop.
Lua interacts with C
#include "lua.h"
#include "lauxlib.h"
int l_bar(lua_State *L)
{
const char *str = lua_tostring(L, -1);
int length;
while (1) {
char c = str[length];
if (c == '\0')
break;
length++;
}
lua_pushstring(L, str);
lua_pushnumber(L, length);
return 2;
}
int l_WriteOut(lua_State *L)
{
const char *str = lua_tostring(L, -1);
printf("%s", str);
return 0;
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_dofile(L, "test.lua");
lua_pushcfunction(L, l_bar);
lua_setglobal(L, "bar");
lua_pushcfunction(L, l_WriteOut);
lua_setglobal(L, "WriteOut");
lua_getglobal(L, "foo");
if (lua_isnil(L, -1)) {
printf("The number is nil!\n");
} else {
lua_pushstring(L, "cheeseburger");
lua_pcall(L, 1, 1, 0);
int result = lua_tonumber(L, -1);
printf("The result is %d\n", result);
lua_pop(L, 1);
}
int total = 0x480000, current, code = 0;
for (current = 0; current <= total; current += 0x1) {
lua_getglobal(L, "ProgressBar");
lua_pushnumber(L, total);
lua_pushnumber(L, current);
lua_pushnumber(L, code);
if (lua_pcall(L, 3, 0, 0) != 0)
lua_error(L);
}
lua_getglobal(L, "x");
int x = lua_tonumber(L, -1);
printf("x = %d\n", x);
return 1;
}
local clock = os.clock
function sleep(n) -- seconds
local t0 = clock()
while clock() - t0 <= n do end
end
foo = function(str)
local s, len = bar(str)
print(s)
return len
end
ProgressBar = function(Total, Current, Code)
local percentage = Current * 100 / Total
if Current < Total then
WriteOut(string.format("Progress... 0x%08X (%.0f%%)\r", Current, percentage))
else
WriteOut(string.format("Progress... Success (%.0f%%) \n", percentage))
end
-- sleep(1)
end
x = 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment