Created
September 8, 2012 06:54
-
-
Save Vesnica/3672425 to your computer and use it in GitHub Desktop.
Embed Lua example
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
avg, sum = average(10, 20, 30, 40, 50) | |
print("The average is ", avg) | |
print("The sum is ", sum) | |
print("Versioin is ", VERSION) |
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 <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