Chinaunix首页 | 论坛 | 博客
  • 博客访问: 857382
  • 博文数量: 254
  • 博客积分: 5350
  • 博客等级: 大校
  • 技术积分: 2045
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-27 13:27
文章分类

全部博文(254)

文章存档

2015年(1)

2014年(9)

2013年(17)

2012年(30)

2011年(150)

2010年(17)

2009年(28)

2008年(2)

分类: C/C++

2013-02-26 16:50:28

lua 与c/c++的变量交换,调用方法


点击(此处)折叠或打开

  1. /*
  2.  * main.cpp
  3.  *
  4.  * Created on: 2013-1-9
  5.  * Author: root
  6.  */
  7. #include <lua.hpp>
  8. #include <iostream>

  9. using namespace std;

  10.     void InitLua(lua_State *L)
  11.     {
  12.         luaL_openlibs(L);
  13.         if(luaL_dofile(L,"test.lua"))
  14.         {
  15.             cout << "can't load test.lua" << endl;
  16.         }
  17.     }

  18.     //get global statues value from lua
  19.     template<class T>
  20.     class GetLuaData
  21.     {
  22.     public:
  23.         GetLuaData(){}
  24.         ~GetLuaData(){}

  25.         inline T PopLuaNumber(lua_State* pL, const char* name)
  26.             {
  27.                 lua_settop(pL,0);
  28.                 lua_getglobal(pL,name);
  29.                 //check variable is the correct type
  30.                 if(!lua_isnumber(pL,1))
  31.                 {
  32.                     cout << "n[C++]:Error: Invalid type!";
  33.                 }
  34.                 T val = (T)lua_tonumber(pL,1);
  35.                 lua_pop(pL,1);
  36.                 return val;
  37.             }

  38.         inline string PopLuaTableString(lua_State* pL, const char* tableName,const char* var)
  39.         {
  40.             lua_settop(pL,0);
  41.             lua_getglobal(pL,tableName);//把表放堆栈上
  42.             if(!lua_istable(pL,1))
  43.             {
  44.                 cout << "n[c++]:Error, " << tableName << " is not a valid table" << endl;
  45.             }

  46.             lua_pushstring(pL,var);//把键放堆栈上
  47.             if(!lua_isstring(pL,-1))
  48.             {
  49.                 cout << "n[c++]:Error invalid type!" << endl;
  50.             }
  51.             lua_gettable(pL,-2);// 出棧键值,把键对应表里的数据放在堆栈里键刚才所在的位置
  52.             string sname;
  53.             if(lua_isstring(pL,-1))
  54.             {
  55.                 sname = lua_tostring(pL,-1);
  56.             }
  57.             lua_pop(pL,1);
  58.             return sname;
  59. //            else if(lua_isnumber(pL,-1))
  60. //            {
  61. //                T name = (T)lua_tonumber(pL,-1);
  62. //                return name;
  63. //            }
  64.         }

  65.     };


  66. int main(int argc,char* argv[])
  67. {
  68. //    lua_State *L = lua.open();
  69.     lua_State *L = luaL_newstate();
  70. //    luaL_openlibs(L);
  71. //    luaL_dofile(L, "test.lua");
  72.     InitLua(L);

  73. //    lua_settop(L,0);
  74. //    lua_getglobal(L,"user_score");
  75. //    lua_getglobal(L,"comp_score");
  76. //    if(!lua_isnumber(L,1) || !lua_isstring(L,2))
  77. //    {
  78. //        cout << "n[C++]: Error: Invalid type!";
  79. //    }

  80. //    string a = lua_tostring(L,1);
  81. //    string b = lua_tostring(L,2);
  82. //    int a = (int)lua_tonumber(L,1);
  83. //    int b = (int)lua_tonumber(L,2);
  84.     GetLuaData<int> tmpLua;
  85.     int a = tmpLua.PopLuaNumber(L,"user_score");
  86.     int b = tmpLua.PopLuaNumber(L,"comp_score");
  87.     cout << " a = " << a << " b = " << b << endl;

  88.     string c = tmpLua.PopLuaTableString(L,"simple_table","name");
  89.     cout << " name = " << c << endl;

  90. //lua function,C,C++中调用lua的函数
  91.     lua_getglobal(L,"add");
  92.     if(!lua_isfunction(L,-1))
  93.     {
  94.         cout << "nn[c++]:Ops! The lua function 'add' has not been defined";
  95.     }
  96.     else
  97.     {
  98.         lua_pushnumber(L,5);
  99.         lua_pushnumber(L,8);
  100.         lua_call(L,2,1);
  101.         int result = (int)lua_tonumber(L,-1);
  102.         lua_pop(L,1);
  103.         cout << "result = " << result << endl;
  104.     }


  105.     lua_close(L);

  106.     return 0;
  107. }
  108. //=========================C,C++函数暴露给lua,调用==============================
  109. //C函数,不能直接被调用,需要使用一个包装函数以满足调用方式
  110. void EvaluateTheGuess(string user_guess,string comp_guess,int &user_score,int &comp_score)
  111. {

  112. }
  113. int cpp_EvaluateTheGuesses(lua_State* pL)
  114. {
  115.     int n = lua_gettop(pL);
  116.     if( n != 4 )
  117.     {
  118.         std::cout << "n[c++]: Wrong number of arguments for cpp_EvaluateTheGuesses";
  119.     }

  120.     if(!lua_isstring(pL,1) || !lua_isstring(pL,2) ||
  121.             !lua_isnumber(pL,3) || !lua_isnumber(pL,4))
  122.     {
  123.         std::cout << "n[c++]: Error: Invalid types passed to cpp_evaluateTheGuesses";
  124.     }

  125.     std::string user_guess = lua_tostring(pL,1);
  126.     std::string comp_guess = lua_tostring(pL,1);
  127.     int                        user_score    =(int)lua_tonumber(pL,3);
  128.     int                        comp_score = (int)lua_tonumber(pL,4);

  129.     EvaluateTheGuess(user_guess,comp_guess,user_score,comp_score);

  130.     lua_pushnumber(pL,user_score);
  131.     lua_pushnumber(pL,comp_score);

  132.     return 2;
  133. }
  134. // lua中注册后可以调用cpp_EvaluateTheGuesses函数
  135. int regFunction(lua_State* pL)
  136. {
  137.     lua_register(pL,"cpp_EvaluateTheGuesses",cpp_EvaluateTheGuesses);
  138.     return 1;
  139. }

lua 测试脚本


点击(此处)折叠或打开

  1. simple_table = {name="Dan dare", age=20}
  2. function add(a,b)
  3.   return (a+b)
  4. end
  5. math.randomseed(os.time())
  6. user_score = 0
  7. comp_score = 0
  8. lookup = {};
  9. lookup["rock"] = {rock = "draw",paper = "lose", scissors = "win" }
  10. lookup["paper"] = {rock= "win", paper = "draw", scissors = "lose"}
  11. lookup["scissors"] = {rock = "lose", paper = "win", scissors = "draw"}

  12. function GetAIMove()
  13.     local int_to_name = {"scissors","rock","paper"}
  14.     return int_to_name[math.random(3)]
  15. end

  16. function EvaluateTheGuesses(user_guess,comp_guess)
  17.     print("user guess... "..user_guess.." comp guess... "..comp_guess)
  18.     if (lookup[user_guess][comp_guess] == "win") then
  19.         print("You Win the Round!")
  20.         user_score = user_score + 1
  21.         elseif (lookup[user_guess][comp_guess]) == "lose" then
  22.                 print("Computer wins the Round")
  23.                 comp_score = comp_score + 1
  24.         else
  25.                 print("Draw!")
  26.                 print(lookup[user_guess][comp_guess])
  27.         end
  28.     end
  29.     
  30.     --[[主游戏循环]]
  31.     print("enter q to quit game");
  32.     print()
  33.     loop = true
  34.     while loop == true do
  35.         print("User: "..user_score.." computer: "..comp_score)
  36.         user_guess = io.stdin:read '*l'
  37.         local letter_to_string = {s = "scissors", r = "rock", p = "paper"}
  38.         if user_guess == "q" then
  39.             loop = false
  40.         elseif    (user_guess == "r") or (user_guess == "p") or (user_guess == "s") then
  41.             comp_guess = GetAIMove()
  42.             EvaluateTheGuesses(letter_to_string[user_guess],comp_guess)
  43.         else
  44.             print("Invalid input, try again")
  45.         end
  46.     end


阅读(1104) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~