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

Optional Arguments

Started by thedobbles, 09 January 2015 - 03:17 PM
thedobbles #1
Posted 09 January 2015 - 04:17 PM
Hello, internet! I am back with another issues (Dun, dun duuuuuh)! I was wondering if and how it was possible to make a function with an optional argument. An example is
rednet.send(message, id, [protocol]
In this case, the protocol argument is optional. Thanks!

-The Dobbles
Edited on 09 January 2015 - 03:17 PM
Agent Silence #2
Posted 09 January 2015 - 04:29 PM

function foo(bar,...)
local notRiggedArgs = {...}
if notRiggedArgs[1] ~= nil then
print("OPTIONAL ARGUMENT!!!!one")
else
print("no optional argument awww")
end
end
Edited on 09 January 2015 - 03:29 PM
KingofGamesYami #3
Posted 09 January 2015 - 04:56 PM
Taken from the rednet api:


function send( nRecipient, message, sProtocol )
    -- Generate a (probably) unique message ID
    -- We could do other things to guarantee uniqueness, but we really don't need to
    -- Store it to ensure we don't get our own messages back
    local nMessageID = math.random( 1, 2147483647 )
    tReceivedMessages[ nMessageID ] = true
    tReceivedMessageTimeouts[ os.startTimer( 30 ) ] = nMessageID

    -- Create the message
    local nReplyChannel = os.getComputerID()
    local tMessage = {
        nMessageID = nMessageID,
        nRecipient = nRecipient,
        message = message,
        sProtocol = sProtocol,
    }

    if nRecipient == os.getComputerID() then
        -- Loopback to ourselves
        os.queueEvent( "rednet_message", nReplyChannel, message, sProtocol )

    else
        -- Send on all open modems, to the target and to repeaters
        local sent = false
        for n,sModem in ipairs( peripheral.getNames() ) do
            if isOpen( sModem ) then
                peripheral.call( sModem, "transmit", nRecipient, nReplyChannel, tMessage );
                peripheral.call( sModem, "transmit", CHANNEL_REPEAT, nReplyChannel, tMessage );
                sent = true
            end
        end
    end
end

https://github.com/alekso56/ComputercraftLua/blob/master/rom/apis/rednet
Lignum #4
Posted 09 January 2015 - 05:29 PM
You guys are making it more complicated than it is :P/>.
Any argument that isn't passed is nil.

local function printSomeText(text1, text2)
   print(text1 or "") --# Pass text1 to print, or an empty string (will still make a new line) if text1 is nil.
   print(text2 or "") --# Same as above but with text2.
end

printSomeText("hello", "world") --# Prints
                                        --# hello
                                        --# world
printSomeText("hello") --# Prints hello and an empty line.
printSomeText() --# Prints two empty lines.
Edited on 09 January 2015 - 04:30 PM