如何自动创建 Lua 个表

How to create Lua tables automatically

我正在为一种非常简单的编程语言开发一个非常简单的解释器,我目前正在尝试提取一段代码来解释是否满足条件。目前,要评估的代码位于关键字 compareendcompare 之间,我希望发生的情况如下:

基本上:

original = {"a", "b", "c", "compare", "this", "please", "whatever", "endcompare", "d"}

在这个 "magic" 函数之后,生成以下内容:

new = {"a", "b", "c", "compare", "d"}
c = {"this", "please", "whatever"}

在这种情况下,new将被计算,当遇到关键字compare时,计算c和return回到new

到目前为止,我已经进行了几次尝试,并且 none 已经成功,除非你计算反转部分 table 或跳过所有其他标记...

我将如何创建所述 table?

我认为这会满足您的需求,但我还没有测试过:

function produceTwo(original)
 local newT, c, go = {}, {}, false
 for i,v in ipairs(original) do
  if v == "compare" then
   go = true
   continue
  elseif v == "endcompare" then
   go = false
   continue
  end

  if go then
   table.insert(c, v) 
  else
   table.insert(newT, v)
  end
 end
 return newT, c
end