lua and C/C++

http://www.gamedev.net/page/resources/_/technical/game-programming/the-lua-tutorial-r2999ios

 

  1 // luatest.cpp : Defines the entry point for the console application.
  2 //
  3 
  4 #include "stdafx.h"
  5 
  6 #include <lua.hpp>
  7 #include <iostream>
  8 
  9 class CGameData
 10 {
 11 public:
 12     CGameData( int i ) { m_iLockpickLevel = i; }
 13     int m_iLockpickLevel;
 14 };
 15 
 16 char *szLua =
 17 "function game_door_check( context ) "
 18 "  local x = GetLockpickLevel( context ) "
 19 "  return ( x > 7 ) "
 20 "end ";
 21 
 22 int lua_GetLockpickLevel( lua_State *luaState )
 23 {
 24     try
 25     {
 26         // 檢查參數數量
 27         int nArgs = lua_gettop( luaState );
 28         if( nArgs != 1 )
 29         {
 30             throw( std::exception( "Script Error 1" ) );
 31         }
 32         // 獲取參數,由於咱們知道這裏的參數是什麼,因此能夠cast到咱們所知道的類型
 33         CGameData *pData = (CGameData *) lua_touserdata( luaState, 1 );
 34         if( !pData )
 35         {
 36             throw( std::exception( "Script Error 2" ) );
 37         }
 38         if( pData->m_iLockpickLevel < 0 )
 39         {
 40             throw( std::exception( "logic error" ) );
 41         }
 42         // 壓入棧,做爲返回值
 43         lua_pushinteger( luaState, pData->m_iLockpickLevel );
 44     }
 45     catch( std::exception const &e )
 46     {
 47         // 若是有錯誤,通知lua
 48         lua_pushstring( luaState, e.what() );
 49         lua_error( luaState );
 50     }
 51     return( 1 );
 52 }
 53 
 54 int _tmain(int argc, _TCHAR* argv[])
 55 {
 56     // lua_State就是一個執行代碼的狀態機
 57     lua_State *lState = luaL_newstate(); 
 58     // 初始化這個狀態機: lState
 59     luaL_openlibs( lState ); 
 60 
 61     // 幫助LUA註冊native 函數。一個名字和函數指針的pair,貌似不一樣的狀態機能夠有不一樣的native函數表
 62     lua_register( lState, "GetLockpickLevel", lua_GetLockpickLevel ); 
 63 
 64     // 讓狀態機讀入須要執行的代碼,lua提供其餘方式好比從文件直接讀入
 65     int iStatus = luaL_loadstring( lState, szLua ); 
 66     if( iStatus )
 67     {
 68         std::cout << "Error: " << lua_tostring( lState, -1 );
 69         return 1;
 70     }
 71 
 72     // 執行lua代碼,注意錯誤檢查
 73     iStatus = lua_pcall( lState, 0, 0, 0 );
 74     if( iStatus )
 75     {
 76         std::cout << "Error: " << lua_tostring( lState, -1 );
 77         return 1;
 78     }
 79 
 80     // 經過函數名字讓lua準備好調用這個函數
 81     lua_getfield( lState, LUA_GLOBALSINDEX, "game_door_check" );
 82     CGameData Data( 8 );
 83     // 將這個參數壓入棧
 84     lua_pushlightuserdata( lState, (void *) &Data );
 85     // 執行這個函數
 86     iStatus = lua_pcall( lState, 1, 1, 0 );
 87     if( iStatus )
 88     {
 89         std::cout << "Error: " << lua_tostring( lState, -1 );
 90         return 1;
 91     }
 92 
 93     // 獲取返回值
 94     int iRet = (int) lua_toboolean( lState, -1 );
 95     if( iRet )
 96         std::cout << "Door opened!" << std::endl;
 97     else
 98         std::cout << "Door still closed." << std::endl;
 99 
100     lua_close( lState );
101 
102     return 0;
103 }
相關文章
相關標籤/搜索