【问题标题】:What is the lua equivalent of Python list.pop()?Python list.pop() 的 lua 等价物是什么?
【发布时间】:2011-09-21 02:28:44
【问题描述】:

我正在开发一个项目,最终用户将运行 Lua,并与用 Python 编写的服务器进行通信,但我找不到在 Lua 中做我需要做的事情的方法。

我给程序一个输入:

recipient command,argument,argument sender

我得到一个列表的输出,其中包含:

{"recipient", "command,argument,argument", "sender"}

然后,将这些项目分成单独的变量。之后,我会将command,argument,argument 分离到另一个列表中,然后再次将它们分离到变量中。

我是如何在 Python 中做到的:

test = "server searching,123,456 Guy" #Example
msglist = test.split()
recipient = msglist.pop(0)
msg = msglist.pop(0)
id = msglist.pop(0)

cmdArgList = cmd.split(',')
cmd = cmdArgList.pop(0)
while len(cmdArgList) > 0:
    argument = 1
    locals()["arg" + str(argument)]
    argument += 1

【问题讨论】:

    标签: python list lua equivalent


    【解决方案1】:

    你标题中的问题是要求一些非常具体的东西:Lua 相当于从数组中获取一个值并删除它。那将是:

    theTable = {};  --Fill this as needed
    local theValue = theTable[1];  --Get the value
    table.remove(theTable, 1);     --Remove the value from the table.
    

    您在帖子中提出的问题似乎非常开放。

    【讨论】:

    • 这将起作用,假设 lua 的 split() 创建了一个表。需要额外的一行,但没关系。
    • 除非你使用一些提供它的 Lua 模块,否则 Lua 没有split 函数。它具有模式匹配,您可以使用它来达到相同的效果。
    • 我找到了一个包含各种拆分功能的页面,所以pop是我真正需要的。而且我敢肯定,通过更多的搜索,我可以为当地人找到一些东西()。
    【解决方案2】:

    如果我是你,我不会尝试按原样移植 Python 代码。这是在 Lua 中实现相同功能的更简单的方法:

    local test = "server searching,123,456 Guy"
    local recipient,cmd,args,id = s:match("(.+) (.-),(.+) (.+)")
    

    在这一步之后recipient 是“服务器”,cmd 是“搜索”,args 是“123,456”,id 是“Guy”。

    我不太明白你想用locals()["arg" + str(argument)]做什么,显然你还没有发布你的所有代码,因为一直访问本地arg1有点没用......但如果你想迭代参数只需使用string.gmatch:

    for arg in args:gmatch("[^,]+") do
      -- whetever you want with arg
    end
    

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 1970-01-01
      • 2011-09-03
      • 2011-03-07
      • 2018-02-04
      • 2021-06-19
      • 2013-10-18
      • 2019-04-02
      • 2012-03-20
      相关资源
      最近更新 更多