test.lua
width=200
height=300
weight="this is String"
function LuaInput()
a=io.read();
print(a)
end
function max(num1,num2 )
LuaInput()
if(num1>num2)then
return num1
else
return num2
end
end
html = [[
块状字符串
]]
print(html)
---在此处调用C++方法
findWay()
useLua.cpp
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#pragma comment(lib, "lua53.lib")//这个是在官网下载后源文件编译生成的静态库
lua_State *L;
double Cmax(double x, double y) {
lua_getglobal(L, "max");
lua_pushnumber(L, x);
lua_pushnumber(L, y);
if (lua_pcall(L, 2, 1, 0) != 0) {
printf( "error running function 'f': %s\n", lua_tostring(L, -1));
}
if(!lua_isnumber(L,-1))
printf("function 'f' must return a number\n");
double z = lua_tonumber(L, -1);
lua_pop(L, 1);
return z;
}
lua_Integer getLuaInt(lua_State *L, int index) {//简化函数名
return lua_tointeger(L, index);
}
lua_Integer getLuaInt(int index) {//简化函数参数
return lua_tointeger(L, index);
}
const char * getLuaStr(lua_State *L, int index) {//简化函数名
return lua_tostring(L, index);
}
const char * getLuaStr(int index) {//简化函数参数
return lua_tostring(L, index);
}
int findWay() {
cout << "寻路指令被执行" << endl;
return 1;
}
extern "C" int findWay(lua_State *L) {
return findWay();
}
int main()
{
L = luaL_newstate();
luaL_openlibs(L);
lua_register(L, "findWay", findWay);
//内部自己执行
//luaL_dostring(L, "findWay()");
//脚本文件执行
luaL_dofile(L,"test.lua");
/*
if (luaL_loadfile(L, "test.lua") || lua_pcall(L, 0, 0, 0)) {
printf("error%s\n", lua_tostring(L, -1));
return -1;
}
lua_getglobal(L, "width");
lua_getglobal(L, "height");
lua_getglobal(L, "weight");
printf("width = %d\n", getLuaInt(-3));
printf("length = %d\n", getLuaInt(L, -2));
printf("weight = %s\n", lua_tostring(L, -1));
printf("weight = %s\n", getLuaStr(L, -1));
printf("weight = %s\n", getLuaStr( -1));
printf("%f\n", Cmax(9.0, 11.0));*/
lua_close(L);
system("pause");
return 0;
}