快速转储从Lua传递到C的大表

时间:2018-07-01 17:09:05

标签: lua lua-table luac

为了快速保存包含大型一维数组的Lua表(数组的数目是已知的,但是元素的数目不是固定的。每个数组中大约有800,000个元素),我计划在按照方式-

#include "lua.h"
#include "lauxlib.h"
#include <stdio.h>
#include <assert.h>

static int save_table(lua_State *L) {
  assert(L && lua_type(L, -1) == LUA_TTABLE);

  int len, r;
  void *ptr;
  FILE *f;

  lua_pushstring(L, "p");
  lua_gettable(L, -2);
  len = lua_objlen(L, -1);
  ptr = lua_topointer(L, -1);

  f = fopen("p.bin", "wb");
  assert(f);
  r = fwrite(ptr, sizeof(int), len, f);
  printf("[p] wrote %d elements out of %d requested\n", r, len);
  fclose(f);

  lua_pop(L, 1);

  lua_pushstring(L, "q");
  lua_gettable(L, -2);
  len = lua_objlen(L, -1);
  ptr = lua_topointer(L, -1);

  f = fopen("q.bin", "wb");
  assert(f);
  r = fwrite(ptr, sizeof(float), len, f);
  printf("[q] wrote %d elements out of %d requested\n", r, len);
  fclose(f);

  lua_pop(L, 1);

  return 1;
}

int luaopen_savetable(lua_State *L) {
  static const luaL_reg Map[] = {{"save_table", save_table}, {NULL, NULL}};

  luaL_register(L, "mytask", Map);
  return 1;
}

Lua代码如下所示-

-- sample table containg two 1-d array
my_table = {p = {11, 22, 33, 44}, q = {0.12, 0.23, 0.34, 0.45, 0.56}}

require "savetable"
mytask.save_table(my_table)

上面的代码生成两个内容错误的二进制文件。怎么了?

PS:我正在使用Lua 5.1。我不确定这是否是转储大型Lua表的最快方法。总是欢迎提出建议。

0 个答案:

没有答案