Collection[‘key’] vs Collection.key vs Collection[key] vs Collection[1]Lists

Collection[‘key’] vs Collection.key vs Collection[key] vs Collection[1]Lists

In HaasScript and Lua, the syntax for accessing elements in tables (associative arrays) can be a bit confusing. Here’s a quick breakdown of the different syntaxes:

Collection['key']

This syntax is used to access an element with a string key in the table. In this case, ‘key’ is the string key in the table ‘Collection’. It is the most general form of table indexing, as it allows any string as a key.

Collection.key

This syntax is used to access an element with a string key in the table and is a shorthand for Collection[‘key’]. It can be used when the key is a valid Lua identifier (i.e., it does not contain spaces or special characters, and is not a Lua keyword). It is just a more convenient way to access table elements with string keys that are valid Lua identifiers.

Collection[key]

This syntax is used to access an element in the table with a variable key. In this case, ‘key’ is a variable that contains the key you want to access in the table ‘Collection’. It is a more flexible way of accessing elements, as it allows you to use any value (number, string, etc.) as the key.

Collection[1]

This syntax is used to access an element in the table with a numeric index. In this case, ‘1’ is the numeric index of the element you want to access in the table ‘Collection’. It is useful when working with lists (tables with numeric indices) or arrays.

Summary

Collection[‘key’] and Collection.key are used for accessing elements with string keys, Collection[key] is used for accessing elements with variable keys, and Collection[1] is used for accessing elements with numeric indices.

Back to: HaasScript Fundamentals > Using Data