memo : lua_strlen

lua_strlenの実験コード。luaでは文字列中のNULLも文字として含まれる。

#include <cstdio>
#include <cassert>
#include <lua.hpp>

int main(int argc, char* argv[])
{
  int 		 top;
  lua_State 	*L;

  L = luaL_newstate();
  luaL_openlibs(L);

  lua_pushlstring(L, "ABC" "\x00" "DEF", 7);

  top = lua_gettop(L);

  printf("len = %d\n", lua_strlen(L, top));

  lua_close(L);
  return 0;
}
% ./a.out
len = 7

lua_pushlstringではなくlua_pushstring('l'がない)を使うとNULL文字までの文字列がスタックに積まれ、len=3になる。

この例では lua_pushlstringで長さ指定付きでスタックに入れているが、スクリプトで変数定義したのをスタックに積んでも結果は同じ。

#include <cstdio>
#include <cassert>
#include <lua.hpp>

int main(int argc, char* argv[])
{
  int 		 top;
  lua_State 	*L;

  L = luaL_newstate();
  luaL_openlibs(L);

  if ( luaL_loadfile(L, argv[1]) || lua_pcall(L, 0,0,0) )
    {
      fprintf(stderr, "cannnot load config file : %s\n", lua_tostring(L, -1));
      return 0;
    }

  lua_getglobal(L, "teststr");

  top = lua_gettop(L);

  printf("len = %d\n", lua_strlen(L, top));
  printf("%s\n", lua_tostring(L,-1));

  lua_close(L);
  return 0;
}

読み込ませるluaスクリプト x.lua

-- 長さは11になるはず
teststr = "Hello" .. string.char(0) .. "World"
% ./a.out x.lua
len = 11
Hello