Skip to content

Instantly share code, notes, and snippets.

@Vesnica
Created September 8, 2012 06:54
Show Gist options
  • Save Vesnica/3672425 to your computer and use it in GitHub Desktop.
Save Vesnica/3672425 to your computer and use it in GitHub Desktop.
Embed Lua example
avg, sum = average(10, 20, 30, 40, 50)
print("The average is ", avg)
print("The sum is ", sum)
print("Versioin is ", VERSION)
#include <stdio.h>
#include <stdlib.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
/* The function we'll call from the lua script */
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++)
{
if (!lua_isnumber(L, i))
{
lua_pushstring(L, "Incorrect argument to 'average'");
lua_error(L);
}
/* 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;
}
/* the Lua interpreter */
lua_State* L;
#define VERSION "0.7"
int main ( int argc, char *argv[] )
{
int sum;
/* initialize Lua */
L = luaL_newstate();
luaL_openlibs(L);
lua_pushstring(L, VERSION);
lua_setglobal(L, "VERSION");
lua_register(L, "average", average);
luaL_dofile(L, "average.lua");
/* cleanup Lua */
lua_close(L);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment