How to dissect and parse a string in lua?

后端 未结 3 1480
南旧
南旧 2021-01-25 13:58

I am trying to make command arguments in Roblox. For example, /kill playername. The problem is I don\'t know how to parse the playername from the string /kill

相关标签:
3条回答
  • 2021-01-25 14:36

    If you want this to be more flexible to more commands in the future, I suggest you take both lhf's and BotOfWar's suggestions and combine them.

    local function executeCommandInMessage(message)
        -- do a quick regex of the message to see if it is formatted as a command
        -- all we care about is the command, any arguments are optional.
        local command, arguments = string.match(message, "^/(%w+)[%s]?([%w%s]+)$")
    
        if command ~= nil then
            -- we've found a command, parse the arguments into groups of non-space characters
            -- then store each word in the parts array
            local parts = {}
            for w in arguments:gmatch("%S+") do
                table.insert(parts, w)
            end
    
            -- handle each command individually
            if command == "kill" then
                local player = parts[1]
                print(string.format("Killing %s", player))
    
            elseif command == "setdata" then
                local player = parts[1]
                local value = parts[2]
                local amount = parts[3]
                print(string.format("Setting %s on %s to %s", value, player, amount))
    
            -- add any further commands to the list..
            -- elseif command == "" then
            end
        end
    end
    
    
    -- listen for any message submitted by players
    game:GetService("Players").PlayerAdded:Connect(function(Player)
        Player.Chatted:Connect(function(msg)
            -- check for any commands
            executeCommandInMessage(msg)
        end)
    end)
    

    In the future, if you need a better regex to parse the message, I suggest you take a look at how to do Lua pattern matching. They're pretty easy to read once you know what to look at.

    0 讨论(0)
  • 2021-01-25 14:36

    I suggest splitting the string with the string.split method to get the segments, then check if the first value is what you want.

    game:GetService("Players").PlayerAdded:Connect(function(Player)
        Player.Chatted:Connect(function(Message)
            local segments = Message:split(" ")
            if((#segments >= 1) and (segments[1] == "/kill")) then
                -- The rest of the arguments can be accessed like this:
                local args = {unpack(segments, 2)} -- Gets every argument after the first value,
                -- which is the command.
            end
        end)
    end)
    
    0 讨论(0)
  • 2021-01-25 14:44

    Use string.match:

    Message=" /kill playername  "
    command, arg = Message:match("%s*/(.-)%s+(.*)%s*$")
    
    0 讨论(0)
提交回复
热议问题