如何在Lua中打印连接的字符串表?

时间:2014-03-14 14:40:29

标签: lua

好的我正在为我的Oxide Lua插件编写一个脚本,我也正在学习Lua Script,所以我不确定如何做到这一点。

-- *******************************************
-- Broadcasts a Server Notification 
-- *******************************************
function PLUGIN:cmdNotice( netuser, args )
  table.concat(args," ")
  local allnetusers = rust.GetAllNetUsers()
  if (allnetusers) then
    for i=1, #allnetusers do
      local netuser = allnetusers[i]
      rust.Notice(netuser, args[1]))
      rust.SendChatToUser(netuser, "Message Sent:" .. args[1])
    end
  end
end

我要做的是解决这个问题,所以我不必手动将我的通知包含在“”中。

例如,正如代码所代表的那样,如果我在使用/notice命令时遇到生锈,我会有两个结果。

示例1

/notice hello everone

只会产生

hello

但如果我这样做

/notice "hello everyone"

会给出完整的信息。所以我有点困惑。

所以我的新代码应该是这样的

-- *******************************************
-- Broadcasts a Server Notification
-- *******************************************
function PLUGIN:cmdNotice( netuser, args )
  table.concat(args," ")
  local allnetusers = rust.GetAllNetUsers()

  if (allnetusers) then
    for i=1, #allnetusers do
      local netuser = allnetusers[i]
      rust.Notice(netuser, table.concat(args, " " ))
      rust.SendChatToUser(netuser, "Message Sent:" .. table.concat(args, " "))
    end
  end
end

编辑2014年3月15日

好吧很酷,因为我也可以做到这一点正确吗?

function PLUGIN:cmdNotice( netuser, args )

    if (not args[1]) then
        rust.Notice( netuser, "Syntax: /notice Message" )
        return
    end
  local allnetusers = rust.GetAllNetUsers()
  if allnetusers then
    for i=1, #allnetusers do
      local netuser = allnetusers[i]
      local notice_msg = table.concat(args," ")
      rust.Notice(netuser, notice_msg)
      rust.SendChatToUser(netuser, "Message Sent:" .. notice_msg)
    end
  end
end

1 个答案:

答案 0 :(得分:3)

为了澄清@EgorSkriptunoff所说的内容,table.concat返回已连接的表,但它不会更改args的值。由于您没有保存连接的返回值,因此函数内的第1行是无用的。作为他的方法的替代方案,您可以rust.SendChatToUser ( netuser, "Message Sent:" .. table.concat(args, " " )

我的猜测是你在考虑(?)连接的字符串是否会作为表格中的第一项保存在args表中?那不是发生了什么。表本身保持不变,因此当您打印args[1]时,您只获得该数组的第一个字符串。它"工作"当你引用消息时,因为在这种情况下整个消息都是一样的,而且数组只有一个arg[1]

这里发生了什么

t = { "hello", "I", "must", "be", "going"}

-- Useless use of concat since I don't save the return value or use it
table.concat(t, " ")

print(t) -- Still an unjoined table
print(t[1]) -- Prints only "hello"

print(table.concat(t, " ")) -- Now prints the return value

修改:在回答后续问题时,请参阅以下代码中的评论:

function PLUGIN:cmdNotice( netuser, args )
  table.concat(args," ") -- This line is not needed.
  local allnetusers = rust.GetAllNetUsers()

  -- Lua doesn't count 0 as false, so the line below probably doesn't do
  -- what you think it does. If you want to test whether a table has more
  -- than 0 items in it, use this:
  -- if #allnetusers > 0 then...
  if allnetusers then
    for i=1, #allnetusers do
      local netuser = allnetusers[i]
      rust.Notice(netuser, table.concat(args, " " ))
      rust.SendChatToUser(netuser, "Message Sent:" .. table.concat(args, " "))
    end
  end
end
相关问题