Created
September 29, 2014 23:04
-
-
Save iyedb/9ef72b60af0b7c5402cb to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <lua.h> | |
#include <lauxlib.h> | |
#include <lualib.h> | |
/* | |
print("Hello from Lua") | |
print("Lua code is capable of reading the value set from C++:",cppvar) | |
luavar = cppvar * 3 | |
function myluafunction(times) | |
return string.rep("(-)", times) | |
end | |
function myfunction(arg) | |
return cppfunction(arg) | |
end | |
print("this string come from the lua script ö"); | |
*/ | |
static int l_cppfunction(lua_State *L) { | |
double arg = luaL_checknumber(L,1); | |
lua_pushnumber(L, arg * 0.5); | |
return 1; | |
} | |
int main(int argc, char** argv) | |
{ | |
int outfile = open("luaoutput.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); | |
int ret = dup2(outfile, 1); | |
if (ret == -1) | |
perror("dup2"); | |
lua_State *L; | |
L = luaL_newstate(); | |
luaL_openlibs(L); | |
if (luaL_loadfile(L, "luas.lua")) { | |
fprintf(stderr, "*** Something went wrong loading the chunk (syntax error?)\n"); | |
fprintf(stderr, "*** %s\n", lua_tostring(L, -1)); | |
lua_pop(L,1); | |
} | |
printf("iyed bennour\n"); | |
lua_pushnumber(L, 3.14); | |
lua_setglobal(L, "cppvar"); | |
if (lua_pcall(L,0, LUA_MULTRET, 0)) { | |
fprintf(stderr, "*** Something went wrong during execution\n"); | |
fprintf(stderr, "*** %s\n", lua_tostring(L, -1)); | |
lua_pop(L,1); | |
exit(EXIT_FAILURE); | |
} | |
lua_getglobal(L, "luavar"); | |
double luavar = lua_tonumber(L,-1); | |
lua_pop(L,1); | |
fprintf(stderr, "*** C++ can read the value set from Lua luavar = = %f\n", luavar); | |
fprintf(stderr, "*** Execute a Lua function from C++\n"); | |
lua_getglobal(L, "myluafunction"); | |
lua_pushnumber(L, 5); | |
lua_pcall(L, 1, 1, 0); | |
fprintf(stderr, "*** The return value of the function was %s\n", lua_tostring(L, -1)); | |
lua_pop(L,1); | |
fprintf(stderr, "*** Execute a C++ function from Lua\n"); | |
fprintf(stderr, "*** First register the function in Lua\n"); | |
lua_pushcfunction(L, l_cppfunction); | |
lua_setglobal(L, "cppfunction"); | |
fprintf(stderr, "*** Call a Lua function that uses the C++ function\n"); | |
lua_getglobal(L, "myfunction"); | |
lua_pushnumber(L, 5); | |
lua_pcall(L, 1, 1, 0); | |
fprintf(stderr, "*** The return value of the function was %f\n", lua_tonumber(L, -1)); | |
lua_pop(L,1); | |
fprintf(stderr, "*** Release the Lua enviroment\n"); | |
lua_close(L); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment