This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
lzRipTide3zl's profile picture

Read() that stores arguments using a space

Started by lzRipTide3zl, 19 May 2013 - 02:54 PM
lzRipTide3zl #1
Posted 19 May 2013 - 04:54 PM
I recently posted a forum regarding the topic. One guy tried to help and this is what he came up with. The only problem is it has errors.


So basicly I want a program that has a read() function that gets user input and seprates the input in to arguments.


He came up with this code
Spoiler

local function prompt()
        -- Read all of the arguments in as a single string.
        local cmd = read()

        -- Split all of the arguments in the string in 'cmd' by spaces.
        local args = {}
        -- The "[^%s]+" pattern is used to match any sequence of non-space characters
        -- with a size of >= 1.
        for match in string.gmatch (match, "[^%s]+") do
                table.insert (args, match)
        end

        -- Return all of the arguments as a table.
        return args
end

He said run the function with cmd = { prompt() }

the only problem is the prompt() function returns errors
Sammich Lord #2
Posted 19 May 2013 - 04:57 PM
What is the error(s)?
lzRipTide3zl #3
Posted 19 May 2013 - 04:59 PM
What is the error(s)?


returns errors at line 9. says bad argument: string expected, got nil
LBPHacker #4
Posted 19 May 2013 - 05:00 PM
local function prompt()
    -- Read all of the arguments in as a single string.
    local cmd = read()

    -- Split all of the arguments in the string in 'cmd' by spaces.
    local args = {}
    -- The "[^%s]+" pattern is used to match any sequence of non-space characters
    -- with a size of >= 1.
    -- * use cmd instead of match in .gmatch (facepalm)
    for match in string.gmatch(cmd, "[^%s]+") do
            table.insert (args, match)
    end

    -- Return all of the arguments as a table.
    return args
end

-- prompt returns a table, no need of those brackets
local cmd = prompt()
lzRipTide3zl #5
Posted 19 May 2013 - 05:01 PM
local function prompt()
	-- Read all of the arguments in as a single string.
	local cmd = read()

	-- Split all of the arguments in the string in 'cmd' by spaces.
	local args = {}
	-- The "[^%s]+" pattern is used to match any sequence of non-space characters
	-- with a size of >= 1.
	-- * use cmd instead of match in .gmatch (facepalm)
	for match in string.gmatch(cmd, "[^%s]+") do
			table.insert (args, match)
	end

	-- Return all of the arguments as a table.
	return args
end

-- prompt returns a table, no need of those brackets
local cmd = prompt()

Thanks ill try it out
Grim Reaper #6
Posted 19 May 2013 - 05:13 PM
Yeah, that was my bad, sorry.
I fixed the code on your original post.

I meant that you should use

local cmd = { prompt() }
if your return statement was

return unpack (args)