Lua for data representation

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

July 23, 2025 Lua for data representation. My major advocacy is that Lua is a very good general-purpose language. This is not an opinion shared by all. Lua’s major design goal was extending and embedding into existing programs. I think the simplicity and flexibility in design pursued towards the end of that goal extends to make Lua a very good language in general.

2025年7月23日,Lua用于数据表示。我主要主张Lua是一种非常优秀的通用语言,但这并非所有人的共识。Lua的主要设计目标是扩展和嵌入到现有程序中。我认为,为了实现这一目标而追求的设计简洁性和灵活性,使得Lua在总体上也成为了一种非常优秀的语言。

That said, it does its job quite well as an embedding language, and one of its more interesting use cases (and actually, one of its oldest use cases) is as a data or configuration format. Lua’s syntax provides many niceties. For instance, Lua has an infinite family of multiline strings: the most basic one starts with [[ and ends with ]]. However, any amount of equal signs can be put between the two square brackets: print([======[hello, world]======]). The only way to close a [===[ is with an accompanying ]===], not with a ]] or a ]==], or a ]====].

话虽如此,它作为一种嵌入式语言表现得相当出色,而它最有趣的用例之一(实际上也是它最古老的用例之一)是作为数据或配置格式。Lua的语法提供了许多便利。例如,Lua拥有无限系列的跨行字符串:最基本的形式以[[开头并以]]结尾。然而,在两个方括号之间可以放置任意数量的等号:print([======[hello, world]======])。关闭[===[的唯一方法是使用配套的]===],而不是]]、]==]或]====]。

Here is a function that for any string, creates the correct multiline string to represent it:

local function stringize(str)
  local equal_signs = ""
  for e in str:gmatch("](=*)]") do
    if #e >= #equal_signs then equal_signs = e .. "=" end
  end
  return ("[%s[%s]%s]"):format(equal_signs, str, equal_signs)
end

这是一个可以为任何字符串创建正确跨行字符串表示形式的函数:

local function stringize(str)
  local equal_signs = ""
  for e in str:gmatch("](=*)]") do
    if #e >= #equal_signs then equal_signs = e .. "=" end
  end
  return ("[%s[%s]%s]"):format(equal_signs, str, equal_signs)
end

Of course, you can just use string.format with %q, but multiline strings usually provide nicer looking and more compact results. These strings are very good for representing Lua code as strings in other Lua code. Anyway, download this file. If you want to consume massive amounts of memory and possibly crash your computer, run it in CPython. If you want to see “hello, world” printed 5 million times, run it in Lua.

当然,你也可以直接使用带有%q的string.format,但跨行字符串通常能提供更美观、更紧凑的结果。这些字符串非常适合在其他Lua代码中将Lua代码表示为字符串。总之,下载这个文件。如果你想消耗大量内存并可能导致电脑崩溃,请在CPython中运行它。如果你想看到“hello, world”被打印500万次,请在Lua中运行它。

Lua’s parser is designed to handle massive files with stride, which is fairly unique and quite necessary if Lua is to be used for this purpose. Design and implementation choices like these come together to suit Lua for this purpose. I’ve seen 3 main styles of using Lua code to represent data or configuration. I think Lua manages to accommodate each of them well, and each have their appropriate use.

Lua的解析器旨在以步进方式处理大型文件,这相当独特,如果Lua要用于此目的,这是非常有必要的。诸如此类的设计和实现选择共同使Lua适合这一用途。我见过使用Lua代码表示数据或配置的三种主要风格。我认为Lua能够很好地适应每一种风格,并且每种风格都有其适当的用途。

Styles of data representation

JSON style (LON?)

Chunks are much like function bodies. They have return values. So, one thing that one can do is just return a big table from a Lua program.

return {
  foo = "bar",
  list = {1, 2, 3},
  rule_of_thirds = true,
}

数据表示风格

JSON风格(LON?)

代码块非常像函数体,它们有返回值。因此,人们可以做的一件事就是直接从Lua程序中返回一个大表。

return {
  foo = "bar",
  list = {1, 2, 3},
  rule_of_thirds = true,
}

If you’re using this style, you can omit the return and then prepend it when you load the Lua files. This makes any trailing statements syntactically invalid because the return statement must be the last statement in the block. Keep in mind, though, that this does not prevent arbitrary code because function literals can be used instead. return (function() arbitrary_code() end)() Trying to strip out function literals to make this technique safer is fraught and defeats the general elegance of this technique. One can fairly readily use JSON instead.

如果你使用这种风格,可以省略return,并在加载Lua文件时预置它。这会使任何后续语句在语法上无效,因为return语句必须是代码块中的最后一条语句。但请记住,这并不能阻止任意代码的执行,因为可以使用函数字面量来代替。 return (function() arbitrary_code() end)() 试图剔除函数字面量以使该技术更安全是充满风险的,并且破坏了该技术的一般优雅性。人们完全可以直接使用JSON。

INI style

What is often missed about Lua is that it’s subtly full of metaprogrammability. For instance, Lua globals are just stored in a table, and which table is used can be controlled by the code itself. This table is known as the “environment”. An environment may be passed to load as an argument. The way this can be used is that you can load a chunk with an empty environment and then capture the values it sets as globals.

INI风格

关于Lua经常被忽略的一点是,它微妙地充满了元编程能力。例如,Lua的全局变量只是存储在一个表中,而使用哪个表可以由代码本身控制。这个表被称为“环境”。环境可以作为参数传递给load。其用法是,你可以用一个空环境加载一个代码块,然后捕获它设置为全局变量的值。

You can have a file like this:

-- config.lua
foo = "bar"
list = {1, 2, 3}
rule_of_thirds = true

Then, you can get a table with all the configuration as simply as this:

local config = {}
assert(loadfile("config.lua", "t", config))()

你可以拥有这样一个文件:

-- config.lua
foo = "bar"
list = {1, 2, 3}
rule_of_thirds = true

然后,你可以像这样简单地获取包含所有配置的表:

local config = {}
assert(loadfile("config.lua", "t", config))()

Imperative style

Lua has a bit of sugar that allows you to shed the parenthesis on function calls to make them look cleaner. An imperative style is a very suitable means to represent data in Lua, and it’s very powerful.

path "/path/to/things"
config {
  foo = "bar",
  list = {1, 2, 3},
  rule_of_thirds = true,
}
lipsum [[ Voluptatibus laudantium et omnis ut debitis... ]]

Programming in Lua provides a real world example of this.

命令式风格

Lua有一些语法糖,允许你在函数调用时省略括号,使其看起来更整洁。命令式风格是Lua中表示数据的一种非常合适的方法,而且非常强大。

path "/path/to/things"
config {
  foo = "bar",
  list = {1, 2, 3},
  rule_of_thirds = true,
}
lipsum [[ Voluptatibus laudantium et omnis ut debitis... ]]

《Programming in Lua》一书提供了这方面的现实示例。

Security considerations

The major problem with using an entire programming language to represent data is that untrusted data can be readily crafted to be malicious. Indeed, I would not use this technique for untrusted data. With that in mind, it is possible to solve or mitigate the potential vulnerabilities. The main technique for sandboxing Lua is controlling the environment.

安全考量

使用完整的编程语言来表示数据的主要问题在于,不受信任的数据很容易被精心设计成恶意代码。事实上,我不会对不受信任的数据使用这种技术。考虑到这一点,解决或减轻潜在漏洞是可能的。沙盒化Lua的主要技术是控制环境。

When using Lua for data representation, an empty environment is the most appropriate (or, an environment that only exposes data constructors). This prevents any I/O or access to the larger program’s state. Preventing access to all standard library functions is safest. There are a few standard library functions that have consequences you might not expect.

当使用Lua进行数据表示时,空环境是最合适的(或者是一个仅暴露数据构造函数的环境)。这可以防止任何I/O操作或对大型程序状态的访问。禁止访问所有标准库函数是最安全的。有一些标准库函数会产生你可能意想不到的后果。

Another concern is denial of service. This is trickier to prevent. It’s fairly trivial to construct a Lua chunk which does not return (while true do end). debug.sethook can mitigate this somewhat. Even so, it’s probably possible to construct something that uses excessive amounts of memory. That said, denial of service is significantly less problematic than the vulnerabilities that are completely avoided by depriving the untrusted code of any standard library functions.

另一个担忧是拒绝服务攻击。这更难预防。构建一个不返回的Lua代码块(while true do end)相当简单。debug.sethook可以在一定程度上缓解这种情况。即便如此,构建一个消耗大量内存的代码仍然是可能的。话虽如此,拒绝服务攻击的问题远比通过剥夺不受信任代码对任何标准库函数的访问权限而完全避免的漏洞要小得多。

Finally, make sure to reject Lua bytecode. Untrusted Lua bytecode is not safe and may cause arbitrary nasal demons in the Lua interpreter. load can accept both bytecode and Lua source by default. However, passing “t” for the mode parameter prevents this.

最后,请确保拒绝Lua字节码。不受信任的Lua字节码是不安全的,可能会在Lua解释器中导致任意的“鼻恶魔”(未定义行为)。load默认可以接受字节码和Lua源代码。然而,为mode参数传递”t”可以防止这种情况。

Why? Clearly, it’s silly to bring in the entire Lua interpreter where you would just use JSON or INI. Where this use case of Lua shines is when you’re already using Lua for a project (and then you already have this powerful data description language), or when you need something with a lot of power or flexibility. These mini languages can be extended to arbitrary complexity and nuance.

为什么?显然,在可以使用JSON或INI的地方引入整个Lua解释器是很愚蠢的。Lua的这种用例的闪光点在于,当你已经在项目中使用Lua时(此时你已经拥有了这种强大的数据描述语言),或者当你需要某种具有强大功能或灵活性的东西时。这些微型语言可以扩展到任意的复杂度和细微差别。