Skip to content

Commit

Permalink
added Lua to C example
Browse files Browse the repository at this point in the history
  • Loading branch information
shazz committed May 29, 2022
1 parent c535264 commit a1fa81b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
7 changes: 6 additions & 1 deletion libogc2/lualib/lua/script.lua
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,10 @@ for i = 1, #foo do
print(i, foo[i])
x = x + foo[i]
end

io.write("Asking C to compute average and sum and check the equality\n")
avg, sum = average(unpack(foo));

print(x == sum)
io.write("Returning data back to C\n");
return x
return sum
29 changes: 28 additions & 1 deletion libogc2/lualib/source/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ static void reset_cb(u32 irq, void* ctx) {
}

lua_State * LUA_Init() {

lua_State * L;
L = luaL_newstate();

Expand All @@ -48,6 +48,30 @@ lua_State * LUA_Init() {
return L;
}

static int average(lua_State *L)
{
/* get number of arguments */
int n = lua_gettop(L);
double sum = 0;
int i;

/* loop through each argument */
for (i = 1; i <= n; i++)
{
/* total the arguments */
sum += lua_tonumber(L, i);
}

/* push the average */
lua_pushnumber(L, sum / n);

/* push the sum */
lua_pushnumber(L, sum);

/* return the number of results */
return 2;
}

int main(int argc, char *argv[]) {

int is_connected = 0;
Expand Down Expand Up @@ -105,6 +129,9 @@ int main(int argc, char *argv[]) {
break;
}

/* register our function */
lua_register(L, "average", average);

lua_newtable(L);
for (int i = 1; i <= 5; i++) {
lua_pushnumber(L, i); /* Push the table index */
Expand Down

0 comments on commit a1fa81b

Please sign in to comment.