Modifying variables based on function argument

Posted by Gore on Tue 20 Mar 2007 09:06 PM — 5 posts, 20,314 views.

#0
Basically I've got a bunch of functions that go along the lines of:

function reset.drink ()
  if bal.drink == .5 then
    bal.drink = true
  end
end

function reset.salve ()
  if bal.salve == .5 then
    bal.salve = true
  end
end

function reset.herb ()
  if bal.herb == .5 then
    bal.herb = true
  end
end

And so on and so forth, and I was wondering if there was anyway to condense them into one function, such as

function reset.balance (type)

this way I could save space in my script file, any suggestions?
USA #1
Sure.


function reset.balance(type)
  if bal[type] == .5 then
    bal[type] = true
  end
end


In Lua, for a table t, t.str is a shortcut for t["str"]. If you do t[var], that means "look up key var in table t'.
#2
Lua is amazing. Do you know if there's anyway to do that in vbscript? Because I've been trying to figure that out for a long time :(
USA #3
I'm not terribly sure if there's an easier way to do it other than what I'm going to suggest, but there's a simple workaround I've used for a long time. Just an extra value to the function saying what variable to modify. Then just have a case section picking the variable to modify.


function reset( action )
  select action
    case "drink"
      if bal.drink == .5 then
        bal.drink = true
      end
    case "salve"
      if bal.salve == .5 then
        bal.salve = true
      end
    case "herb"
      if bal.herb == .5 then
        bal.herb = true
      end
  end select
end


My only concern is that the value for bal.foo has both decimal values and boolean values in there. It kind of obscures the code a bit, and is harder to follow than just a normal test of bal.foo == 1 for true. Granted, I haven't seen the rest of the script, so it might make sense to have it that way.
Australia Forum Administrator #4
Quote:

Do you know if there's anyway to do that in vbscript?


It would be easy if you had arrays that could have named indexes (rather than numbers). I think there is such a thing, I can't remember offhand what it is.