hello lua

    xiaoxiao2023-02-02  15

    前言

    lua初体验, 用lua-5.3.3做了一次试验.

    记录

    // MyLuaTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> #include <stdlib.h> #include <stdio.h> // 参考资料 // http://lua-users.org/wiki/SampleCode // 试验的lua版本 : lua-5.3.3.tar.gz extern "C" { #include "lua.h" // lua基本api #include "lauxlib.h" // lua扩展api #include "lualib.h" // Lua standard libraries }; #define LUA_FILE_NAME "test.lua" int __cdecl IF_Test(lua_State* L) { // .lua 调用宿主程序接口 IF_Test, 进入这里 // .lua向宿主程序接口传递的参数在L中 const char* pParam1 = NULL; double fParam2 = 0; double fParam3 = 0; double fRc = -1; ///< 宿主程序向.lua返回结果 int iRc = 1; printf(">> IF_Test\r\n"); // 取出.lua提供的参数 pParam1 = luaL_checkstring(L, 1); fParam2 = luaL_checknumber(L, 2); fParam3 = luaL_checknumber(L, 3); if (0 == strcmp("add", pParam1)) { fRc = fParam2 + fParam3; } else if (0 == strcmp("sub", pParam1)) { fRc = fParam2 - fParam3; } lua_pushnumber(L, fRc); // 压入返回值给.lua return LUA_YIELD; // ! 不能是 LUA_OK } int main(int argc, char* argv[]) { lua_State* L = NULL; int iLuaErr = 0; // 创建lua新环境. lua_open被废弃了 L = luaL_newstate(); if (NULL != L) { luaL_openlibs(L); // 打开lua库 // 注册宿主程序的接口函数给lua用 lua_register(L, "IF_Test", IF_Test); iLuaErr = luaL_dofile(L, LUA_FILE_NAME); // 载入lua文件 if (LUA_OK != iLuaErr) { printf("%s\r\n", luaL_checkstring(L, -1)); } lua_close(L); // 关闭lua环境 } system("pause"); return 0; } -- file : test.lua io.write(">> test.lua\r\n"); -- 调用宿主程序接口, 并传参数 addRc = IF_Test("add", 100, 200) -- 使用接口的返回值 print("IF_Test(\"add\", 100, 200) = ", addRc) subRc = IF_Test("sub", 100, 200) print("IF_Test(\"sub\", 100, 200) = ", subRc) io.write("<< test.lua\r\n")

    run result

    >> test.lua >> IF_Test IF_Test("add", 100, 200) = 300.0 >> IF_Test IF_Test("sub", 100, 200) = -100.0 << test.lua 请按任意键继续. . .
    转载请注明原文地址: https://ju.6miu.com/read-1138588.html
    最新回复(0)