ChaiScript/unittests/index_operator_override.chai
leftibot 726169acc8
Fix #398: Allow overriding [] operator with string index on Dynamic_Object subtypes (#667)
The built-in Dynamic_Object::get_attr was always winning dispatch over
user-defined [] overrides when a string index was used, because its C++
type signature (Dynamic_Object, const string&) scored numdiffs=0 while
ChaiScript-defined functions had higher numdiffs due to undefined type
info. The fix deprioritizes generic C++ Dynamic_Object functions when the
actual first argument is a specific subtype, and maps named ChaiScript
type parameters to Dynamic_Object type_info for correct dispatch scoring.

Co-authored-by: leftibot <leftibot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 18:59:09 -06:00

46 lines
674 B
ChaiScript

// Test overriding [] operator with various index types (issue #398)
class my_class
{
def my_class()
{
}
};
def `[]`(my_class o, idx)
{
return "Hello World!";
}
var o = my_class();
// Integer index should work
assert_equal("Hello World!", o[3]);
// String index should work
assert_equal("Hello World!", o["3"]);
// String variable as index should work
var s = "abc";
assert_equal("Hello World!", o[s]);
// Typed string parameter override
class my_class2
{
def my_class2()
{
}
};
def `[]`(my_class2 o, string key)
{
return "key=" + key;
}
var o2 = my_class2();
assert_equal("key=foo", o2["foo"]);
var key = "bar";
assert_equal("key=bar", o2[key]);