lua學習(三)

來源:互聯網
上載者:User

對lua有了個初步的瞭解, 同事按捺不住在項目上面用了一下c api. 由於大家都不熟lua的 c api, 我也去學習一下. 這樣大家可以討論了.
5.1的 luaopen_io()不能用了, 用了一下直接掛掉. 查了一下官方的文檔, 他沒有說清楚.只是說不能直接調用. 不明白 
而且看了一下, lua_open()宏最好由 luaL_newstate()來代替.

首先試了一下對 全域變數的讀取.
width = 100;
height = 200;

執行操作
1. 建立一個lua狀態
2. open要用到的庫, 可以看到棧上就多了幾個表. 我open了base, string和math之後,棧上會壓進四個表.猜猜有可能有一個math表, math表裡面有sin,pi之類的函數或者變數.
3. 載入test.lua檔案,用lua_pcall執行它.這時候width和height的值就全部確定了. 下一步是通過c來得到它們
4. lua_getglobal根據"width"名稱取得width的值, 這個方法會把width的值也就是100壓入棧中
5. 用lua_isnumber判斷得到的是否數字,如果是數字那用lua_tonumber來取得值

這個簡單! 接下來是取表
BLUE = {r=100, g=0, b=1}
執行操作:
1. 建立一個lua狀態
2. open要用到的庫, 可以看到棧上就多了幾個表. 我open了base, string和math之後,棧上會壓進四個表.猜猜有可能有一個math表, math表裡面有sin,pi之類的函數或者變數.
3. 載入test.lua檔案,用lua_pcall執行它.
4. lua_getglobal根據"BLUE "名稱取得BLUE 的值,同時把BLUE 的值,也就是一個BLUE的表壓入棧中.
5. lua_pushstring把'r'壓入棧中,此時棧頂元素為'r', 下面為BLUE表. 也就是'r '的index為-1,Blue表的index為-2
6. 所以用lua_gettable(L, -2);根據index值-2取得這個表, 再由棧頂的key值'r',取得BLUE表的r元素的值代替棧頂的值.這時候棧頂為100,下面就是BLUE表.
7.接下來就是取值了, 在棧頂取值,和以前的一樣 :)  要注意的是, 棧頂的值要pop清掉

再試試多層的表 :
DBServer =
{
    {
        Name    = "__odbc0",
        DSN     = "oracleDB",
        Login   = "onlinegame",
        Passwd  = "aol123"
    }
}

這個預料應該是push一個number取得子表,實驗之後果然和猜想一樣!

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

void error (lua_State *L, const char *fmt, ...)
{
 va_list argp;
 va_start(argp, fmt);
 vfprintf(stderr, fmt, argp);
 va_end(argp);
 lua_close(L);
 exit(EXIT_FAILURE);
}

int main (void)
{
 //int width;
 //int height;

 lua_State *L = lua_open();

 luaopen_base(L);
 luaopen_string(L);
 luaopen_math(L);

 if (luaL_loadfile(L, "test.lua") || lua_pcall(L, 0, 0, 0))
  error(L, "cannot run configuration file: %s", lua_tostring(L, -1));

 
 lua_getglobal(L, "DBServer");
 if (!lua_istable(L, -1))
  error(L, "'DBServer' is not a valid table");

 lua_pushnumber(L, 1);
 lua_gettable(L, -2);
 if (!lua_istable(L, -1))
  error(L, "this is not a valid  table");

 lua_pushstring(L, "Name");
 lua_gettable(L, -2);

 if (!lua_isstring(L, -1))
  error(L, "invalid string");

 printf("結果是: /t `%s' /n", lua_tostring(L, -1));
 
 lua_pop(L, 1);

 lua_close(L);

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.