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

Is there any better way to achieve this?

Started by H4X0RZ, 19 October 2015 - 03:34 PM
H4X0RZ #1
Posted 19 October 2015 - 05:34 PM
I were experimenting a bit with metatables and got this idea:

local meta = {}
function meta.__index(_,k)
  if(k:sub(1,1) == "b" and tonumber(k:sub(2,2))) then
    if(not tonumber(k:sub(2,#k),2)) then error("Invalid binary sequence.",0) end
    return tonumber(k:sub(2,#k),2)
  end
end

function meta.__newindex(t,k,v)
  if(k:sub(1,1) == "b" and tonumber(k:sub(2,2))) then
    error("You can't use this name!",0)
  end
  rawset(t,k,v)
end

_G = setmetatable(_G,meta)

It basically allows you to enter raw binary numbers and they will be "translated" into normal numbers which could be used for math and that stuff. It doesn't have any particular use becuase b100 would be equal to 8 so I could just enter 8 since the beginning.

So, now… Is there any better way to achieve this? maybe something less hacky?
Bomb Bloke #2
Posted 19 October 2015 - 10:39 PM
b100 would be equal to 8

4. :P/>

If you just do k:sub(2), you get every character but the first. It'd be better to do that then to use k:sub(2,2) or k:sub(2,#k); eg:

function meta.__index(_,k)
  if k:sub(1,1) == "b" and tonumber(k:sub(2), 2) then
    return tonumber(k:sub(2), 2)
  else
    error("Invalid binary sequence.",2)
  end
end

Though, I don't get why you don't just make meta.__index(_,k) a regular function called "parseBinaryString" or something. Attaching the function to _G via a metatable doesn't offer any speed advantages; to my understanding it'd be the opposite.

Edit:

Ah, I'm an idiot. You're goal's to be able to type b-whatever straight into your code and have the uninitialised variable resolve to a number directly. Somehow didn't manage to see that before.

I'd still stick with k:sub(2), but I'd suggest rigging __index not to error (and __newindex should probably throw "unexpected symbol"). Though I can't think of a better overall method than using metatables. A regular function would still be more efficient at run-time, but what the heck, Lua's a fairly high-level language anyways.
Edited on 20 October 2015 - 03:45 AM