【问题标题】:Convert table from string in lua从lua中的字符串转换表
【发布时间】:2022-02-04 23:36:17
【问题描述】:

如何将"{'label' = [1, 2]}" 转换为lua 中的表格? 预期答案:{'label' = [1,2]}

【问题讨论】:

  • {'label' = [1,2]} 不是有效的 Lua 语法
  • {['label'] = {1,2}} 或简单的{label = {1,2}}
  • 为什么说“预期答案”?你没试过,看到它不起作用?也因为它是无效的语法,你为什么期望它?
  • 抱歉,我的问题是——基本上我正在从 python 读取 .mat 文件(因为在使用 matio 从 lua 读取文件时,我遇到了“分段错误”),然后将该数据传递给 lua以字符串形式。像这样的东西 - “{'header': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Thu Feb 3 18:29:31 2022', 'version': '1.0', 'globals': [], 'train_patch': 数组([[[[-2.44379087e-02, 8.37826949e-02, -2.50160102e-02], [ 8.32045934e-02, -2.55941117e-02, -4.53651835e-02], [ 7.29143864e -02, -4.53651835e-02, -3.56530781e-02]]]]), 'train_labels': array([[6, 1, 8, ..., 2, 5, 0]])}"跨度>
  • 但是在使用 load() 将此数据转换为表时,我收到错误为 Error - test.lua:56: bad argument #1 to 'load' (function expected, got nil) stack traceback : [C]: 在函数'load' test.lua:56: 在主块中 [C]: 在函数'dofile' ...user/torch/install/lib/luarocks/rocks/trepl/scm-1/bin /th:150: 在主块中 [C]: 在 ?

标签: lua torch


【解决方案1】:

一个充满 Lua 代码的字符串可以用load()“转换”。
在交互式 Lua 控制台中使用的示例...

> _VERSION
Lua 5.4
> tab = 'return {label = {1, 2}}' -- A string for load()
> load(tab)()
table: 0x565fc800
> load(tab)().label
table: 0x565fcd00
> load(tab)().label[1]
1
> load(tab)().label[2]
2

【讨论】:

  • 您好,感谢您的回复。
  • 基本上我正在从 python 读取 .mat 文件(因为在使用 matio 从 lua 读取文件时,我遇到了“分段错误”),然后以字符串形式将该数据传递给 lua。像这样 - "{'header': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Thu Feb 3 18:29:31 2022', 'version': '1.0', 'globals': [], 'train_patch': array([[[[-2.44379087e-02, 8.37826949e-02, -2.50160102e-02], [ 8.32045934e-02,-2.55941117e-02,-4.53651835e-02],[7.29143864e-02,-4.53651835e-02,-3.56530781e-02]]]]),'train_labels':数组([[6 , 1, 8, ..., 2, 5, 0]])}"
  • 但是在使用 load() 将此数据转换为表时,我收到错误为 Error - test.lua:56: bad argument #1 to 'load' (function expected, got nil) stack traceback : [C]: 在函数'load' test.lua:56: 在主块中 [C]: 在函数'dofile' ...user/torch/install/lib/luarocks/rocks/trepl/scm-1/bin /th:150: 在主块中 [C]: 在 ?
  • Lua 5.1? - 比使用loadstring()
  • 使用 loadstring 时输出为零。
猜你喜欢
  • 2014-09-14
  • 2013-12-23
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 2017-11-05
相关资源
最近更新 更多