Created
July 22, 2016 02:26
-
-
Save freem/62afa2291c3d4f71a37ee97fe2330295 to your computer and use it in GitHub Desktop.
an example of when metatables are useful
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ProcessorFlags = { | |
Carry = false, -- 0 | (C) Carry for arithmetic and compares | |
Zero = false, -- 1 | (Z) Set when operation results in 0 | |
IRQ = false, -- 2 | (I) enable/disable IRQ flag | |
Decimal = false, -- 3 | (D) decimal mode | |
Break = false, -- 4 | (B) [only available in stack version] | |
Unused = false, -- 5 | (-) "not used" in regular 6502 (always 1?) | |
Overflow = false, -- 6 | (V) Overflow for arithmetic and compares | |
Sign = false, -- 7 | (N) Negative value result | |
} | |
setmetatable(ProcessorFlags,{ | |
__call = function() | |
-- combine the above flags into a single byte and return. | |
local value = 0; | |
value = value + (ProcessorFlags.Carry and 0x01 or 0) | |
value = value + (ProcessorFlags.Zero and 0x02 or 0) | |
value = value + (ProcessorFlags.IRQ and 0x04 or 0) | |
value = value + (ProcessorFlags.Decimal and 0x08 or 0) | |
value = value + (ProcessorFlags.Break and 0x10 or 0) | |
value = value + (ProcessorFlags.Unused and 0x20 or 0) | |
value = value + (ProcessorFlags.Overflow and 0x40 or 0) | |
value = value + (ProcessorFlags.Sign and 0x80 or 0) | |
return value | |
end, | |
__tostring = function() | |
return (ProcessorFlags.Sign and "N" or "n").. | |
(ProcessorFlags.Overflow and "V" or "v").. | |
(ProcessorFlags.Unused and "-" or "_").. | |
(ProcessorFlags.Break and "B" or "b").. | |
(ProcessorFlags.Decimal and "D" or "d").. | |
(ProcessorFlags.IRQ and "I" or "i").. | |
(ProcessorFlags.Zero and "Z" or "z").. | |
(ProcessorFlags.Carry and "C" or "c") | |
end, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment