All checks were successful
Update pages on webserver / Update (push) Successful in 5s
85 lines
2.5 KiB
Markdown
85 lines
2.5 KiB
Markdown
---
|
|
title: when two macros are faster than one
|
|
draft: "false"
|
|
---
|
|
While working on my Database datapack (still WIP), I knew I'd want to find
|
|
|
|
# scenario
|
|
## dataset
|
|
The data is stored in a storage `#_macro.array`. Array is populated with a total of 500 entries, each having `id` and `string` fields.
|
|
```json
|
|
[
|
|
{
|
|
id: 1,
|
|
string: "entry1"
|
|
},
|
|
...
|
|
{
|
|
id: 500,
|
|
string: "entry500"
|
|
}
|
|
]
|
|
```
|
|
## constraints
|
|
The objective is to create an interface that receives a keyword, say `entry500`, and searches `#_macro.array` for an entry where the value of `string` matches the keyword.
|
|
|
|
The keyword must be able to be entered by a player at runtime, and `#_macro.array` can have an arbitrary number of custom entries created by a player.
|
|
|
|
In TypeScript, it would look something like this:
|
|
```ts
|
|
function searchArray(keyword: string) {
|
|
// logic
|
|
return theRelevantEntry
|
|
}
|
|
|
|
searchArray('entry500')
|
|
```
|
|
In mcfunction, this is not so easy. We *could* use macros
|
|
# one macro
|
|
Macros allow us to reach into our array and pick out an entry that matching value in the `string` property.
|
|
```vb
|
|
... one_macro.array[string:$(keyword)]
|
|
```
|
|
|
|
```vb
|
|
'# one_macro/run.mcfunction
|
|
|
|
data modify storage test_namespace:test_namespace temp.keyword set value 'entry500'
|
|
|
|
function test_namespace:one_macro/_searcharray with storage test_namespace:test_namespace temp
|
|
|
|
data remove storage test_namespace:test_namespace temp.keyword
|
|
data remove storage test_namespace:test_namespace temp.result
|
|
```
|
|
|
|
```vb
|
|
'# one_macro/_searcharray.mcfunction
|
|
|
|
$data modify storage test_namespace:test_namespace temp.result set from storage test_namespace:test_namespace one_macro.array[string:$(keyword)]
|
|
```
|
|
# two macro
|
|
```vb
|
|
'# two_macro/run.mcfunction
|
|
|
|
data modify storage test_namespace:test_namespace temp.keyword set value 'entry500'
|
|
|
|
function test_namespace:two_macro/_searchindex with storage test_namespace:test_namespace temp
|
|
|
|
function test_namespace:two_macro/_searcharray with storage test_namespace:test_namespace temp
|
|
|
|
data remove storage test_namespace:test_namespace temp.keyword
|
|
data remove storage test_namespace:test_namespace temp.index
|
|
data remove storage test_namespace:test_namespace temp.result
|
|
```
|
|
|
|
```vb
|
|
'# two_macro/_searchindex.mcfunction
|
|
|
|
$data modify storage test_namespace:test_namespace temp.index set from storage test_namespace:test_namespace two_macro.index.$(keyword)
|
|
```
|
|
|
|
```vb
|
|
'# two_macro/_searcharray.mcfunction
|
|
|
|
$data modify storage test_namespace:test_namespace temp.result set from storage test_namespace:test_namespace two_macro.array[$(index)]
|
|
``` |