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

Function embedded into list

Started by lifewcody, 01 November 2017 - 04:21 PM
lifewcody #1
Posted 01 November 2017 - 05:21 PM
Hi,

If I have a table like so:

[1] => "this"
[2] => "command"
[3] => "structure"
[4] => "and"
[5] => "my"
[6] => "arguments"

it would call the function (structure) and the rest would be put as arguments? Also this should work dynamically.


["this"] = {
	["command"] = {
		["structure"] = function()
			   -- Get the args, blah blah
		}
	}
}

I currently have a system, but it will only call the first parameter for the function name and put the rest as arguments. In the function I would then have to take care of everything. If I could eliminate that, then it would be easier to make new functions.

Thanks.
KingofGamesYami #2
Posted 01 November 2017 - 06:02 PM

local t = {
    ["this"] = {
            ["command"] = {
                    ["structure"] = print,
            }
    }
}

local function execute( tFuncAndArgs )
  local func = t
  while type( func ) == "table" do
    func = func[ table.remove( tFuncAndArgs, 1 ) ]
  end
  func( table.unpack( tFuncAndArgs ) )
end

execute{ "this", "command", "structure", "hello", "world"}

…but why?
lifewcody #3
Posted 01 November 2017 - 06:21 PM

local t = {
	["this"] = {
			["command"] = {
					["structure"] = print,
			}
	}
}

local function execute( tFuncAndArgs )
  local func = t
  while type( func ) == "table" do
	func = func[ table.remove( tFuncAndArgs, 1 ) ]
  end
  func( table.unpack( tFuncAndArgs ) )
end

execute{ "this", "command", "structure", "hello", "world"}

…but why?

Because I'm making a CLI portion of my program, and if I have a command like >> vlan add interface 001 1 I don't have to check for vlan, add, or interface. I can then just worry about 001 and 1
KingofGamesYami #4
Posted 01 November 2017 - 06:48 PM
I would count "add" and "interface" as arguments because that's what they are. There's no reason to restrict program structure like this.

Take, for example, invalid input. Ideally you should be able to detect which argument is invalid. An if/elseif/else statement would have the "else" as a sort of "catch all", where you can add a customized error message.
Dave-ee Jones #5
Posted 01 November 2017 - 10:36 PM
I would count "add" and "interface" as arguments because that's what they are. There's no reason to restrict program structure like this.

Completely agree. This would make it so you only need the one function, which has the arguments ('add','interface','001','1') passed to it. Easy.
Shark Language does this, btw :P/>
Edited on 01 November 2017 - 09:36 PM