Skip to content

Commit db35730

Browse files
committed
Partial fix for issue #24
1 parent 3f326be commit db35730

File tree

1 file changed

+26
-3
lines changed
  • addons/source-python/plugins/es_emulator/eventscripts/esc/cmds

1 file changed

+26
-3
lines changed

addons/source-python/plugins/es_emulator/eventscripts/esc/cmds/maths.py

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,28 @@
77

88
root = lambda a, b: pow(a, 1.0/b)
99

10+
# https://stackoverflow.com/a/14246007
11+
def correct(value, bits, signed):
12+
base = 1 << bits
13+
value %= base
14+
return value - base if signed and value.bit_length() == bits else value
15+
16+
byte, sbyte, word, sword, dword, sdword, qword, sqword = (
17+
lambda v: correct(v, 8, False), lambda v: correct(v, 8, True),
18+
lambda v: correct(v, 16, False), lambda v: correct(v, 16, True),
19+
lambda v: correct(v, 32, False), lambda v: correct(v, 32, True),
20+
lambda v: correct(v, 64, False), lambda v: correct(v, 64, True)
21+
)
22+
23+
def emulate_datatype_overflow(value):
24+
# int?
25+
if int(value) == value:
26+
# Emulate a signed int
27+
return sdword(value)
28+
29+
# TODO: Handle float overflow
30+
return value
31+
1032
_math_operators = {
1133
'+': add, 'add': add,
1234
'-': sub, 'subract': sub,
@@ -24,16 +46,17 @@ def math(argv):
2446
val = sv[var]
2547
if val.isstring():
2648
raise ValueError('math function called on a non-numeric value: %s, %s' % (var, val.strval))
27-
val = NUM(val)
49+
val = emulate_datatype_overflow(NUM(val))
2850
if op in _math_operators:
2951
if len(argv) < 3:
3052
raise SyntaxError
3153
val2 = argv[2]
3254
if val2.isstring():
3355
raise ValueError('math function called on a non-numeric value: %s' % val2.strval)
34-
sv[argv[0]] = _math_operators[op](val, NUM(val2))
56+
sv[argv[0]] = emulate_datatype_overflow(
57+
_math_operators[op](val, emulate_datatype_overflow(NUM(val2))))
3558
elif op in _math_functions:
36-
sv[argv[0]] = eval(op)(val)
59+
sv[argv[0]] = emulate_datatype_overflow(eval(op)(val))
3760
else:
3861
raise SyntaxError('bad operation "%s"' % op)
3962

0 commit comments

Comments
 (0)