MCPcopy Index your code
hub / github.com/aiscriptdev/aiscript / index

Function index

aiscript-vm/src/builtins/array.rs:191–236  ·  view source on GitHub ↗

Return zero-based index of the first item with value equal to x

(
    _mc: &'gc Mutation<'gc>,
    receiver: Value<'gc>,
    args: Vec<Value<'gc>>,
)

Source from the content-addressed store, hash-verified

189
190// Return zero-based index of the first item with value equal to x
191fn index<'gc>(
192 _mc: &'gc Mutation<'gc>,
193 receiver: Value<'gc>,
194 args: Vec<Value<'gc>>,
195) -> Result<Value<'gc>, VmError> {
196 let list = receiver.as_array()?;
197
198 if args.is_empty() {
199 return Err(VmError::RuntimeError(
200 "index: expected at least 1 argument".into(),
201 ));
202 }
203
204 let value_to_find = &args[0];
205
206 // Get optional start and end parameters
207 let start: usize = if args.len() > 1 {
208 float_arg!(&args, 1, "index")? as usize
209 } else {
210 0
211 };
212
213 let end: usize = if args.len() > 2 {
214 float_arg!(&args, 2, "index")? as usize
215 } else {
216 list.borrow().data.len()
217 };
218
219 // Validate start and end
220 let list_len = list.borrow().data.len();
221 let start = start.min(list_len);
222 let end = end.min(list_len);
223
224 // Search for the value in the specified range
225 for (i, item) in list.borrow().data[start..end].iter().enumerate() {
226 if item.equals(value_to_find) {
227 // Return relative to original list
228 return Ok(Value::Number((i + start) as f64));
229 }
230 }
231
232 Err(VmError::RuntimeError(format!(
233 "index: value {} not found in list",
234 value_to_find
235 )))
236}
237
238// Returns a shallow copy of a portion of the array
239fn slice<'gc>(

Callers

nothing calls this directly

Calls 5

RuntimeErrorClass · 0.85
as_arrayMethod · 0.80
lenMethod · 0.80
borrowMethod · 0.45
equalsMethod · 0.45

Tested by

no test coverage detected