Calling LUA functions in the 1.c\c++ program
Method One:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lua.hpp"
Const char* Lua_function_code = "function dealstr (str) \
Return String.gsub (str,\ "world\", \ "Lua\") \
End ";
void Call_function (lua_state* L)
{
if (lual_dostring (L,lua_function_code))
{
printf ("Failed to run Lua code.\n");
Return
}
Char str[512] = "Hello world!";
Lua_getglobal (L, "dealstr");
Lua_pushlstring (l,str,512);
if (Lua_pcall (l,1,1,0))
{
printf ("Error is%s.\n", lua_tostring (l,-1));
Return
}
if (!lua_isstring (l,-1))
{
printf ("function ' add ' must return a string.\n");
Return
}
size_t Len;
Const CHAR* ret = lua_tolstring (L,-1,&len);
Lua_pop (l,-1); The return value pops up.
printf ("The result of call function is%s.\n", ret);
}
int main ()
{
lua_state* L = Lual_newstate ();
Lual_openlibs (L);
Call_function (L);
Lua_close (L);
System ("pause");
return 0;
}
Method Two:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lua.hpp"
void Call_function (lua_state* L)
{
Lual_dofile (L, "Test.lua");
Char str[512] = "Hello world!";
Lua_getglobal (L, "dealstr");
Lua_pushlstring (l,str,512);
if (Lua_pcall (l,1,1,0))
{
printf ("Error is%s.\n", lua_tostring (l,-1));
Return
}
if (!lua_isstring (l,-1))
{
printf ("function ' add ' must return a string.\n");
Return
}
size_t Len;
Const CHAR* ret = lua_tolstring (L,-1,&len);
Lua_pop (l,-1); The return value pops up.
printf ("The result of call function is%s.\n", ret);
}
int main ()
{
lua_state* L = Lual_newstate ();
Lual_openlibs (L);
Call_function (L);
Lua_close (L);
System ("pause");
return 0;
}
Test.lua
function Dealstr (str)
return string.gsub (str, "World", "LUA")
End
Calling Lua in c\c++