Log In  

With the vast scope that PICO covers in complexity involving multiple arguments and permutations of arrays, I was wondering if there was a way to do something as follows:

function addup(...)
local t=0
  for i=1,#addup()
    t+=arg(i,addup)
  end
  print(t)
end

c={}
c[3]=7
addup(1,2,3,4,5,6,7,8)
addup(1,3,5)
addup()
addup(437,c[3],348,3821)

Where you can call a function with any number of arguments, and all of them are read in turn for the single function.

P#56251 2018-09-05 23:57 ( Edited 2018-09-06 19:17)

PICO-8 does not have Lua's table.unpack(), sadly. And yielding in a coroutine can't return values either, like they can in Lua. Both of those could probably have been used for this.

But in this example, why not just wrap the arguments in curly braces and turn them into a table? The code is almost the same as yours:

function addup(args)
  local t=0
  for i=1,#args do
    t+=args[i]
  end
  print(t)
end

c={}
c[3]=7
addup({1,2,3,4,5,6,7,8})
addup({1,3,5})
addup({})
addup({437,c[3],348,3821})
P#56276 2018-09-06 13:24 ( Edited 2018-09-06 17:25)

And if the table is the only argument, you can even leave out the parentheses. addup{1, 2, 3, 4, 5} will work just fine.

P#56281 2018-09-06 13:45 ( Edited 2018-09-06 17:45)

Really ? You can call a function without parenthesis () if the argument is a table ? {}

Hmm ... That gets my brain spinning, both of you - thanks. I was wondering if the final result was going to be a way to somehow do it with an array, but I didn't know the nomenclature.

Will have to experiment with this marvelous method now. I need a deep level debugger that throws any number of elements into view.

Thanks again !!

P#56285 2018-09-06 14:16 ( Edited 2018-09-06 18:18)

It works well, except for NIL. If I send NIL as an argument, it tosses it out as invalid. Meaning where I am checking for NIL in the code, it never gets reached. It's not too much a problem, if I'm debugging a value, hopefully it already exists.

function db(a)
local t,y,c="",0,peek(24357)
  color(7)
  for i=1,#a do
    y=type(a[i])
    if y=="[nil]" then
      t=t.."-nil- "
    elseif y=="string" then
      if i==1 then
        t=t..a[i].."="
      else
        t=t..'"'..a[i]..'" '
      end
    else
      t=t.."("..a[i]..") "
    end
  end
  print(t)
  color(c)
end
P#56288 2018-09-06 14:30 ( Edited 2018-09-06 18:31)

Easy enough to fix:

for i=1,#(a or {}) do

Or you could use all(), which accepts nil.

P#56292 2018-09-06 14:48 ( Edited 2018-09-06 18:48)

All() breaks the use of A[I].

Using the (a or {}) still exits early if I choose NIL as an argument.

db(nil,5) yields no results.

P#56299 2018-09-06 15:17 ( Edited 2018-09-06 19:17)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-29 06:36:06 | 0.007s | Q:17