Return zero-based index of the first item with value equal to x
(
_mc: &'gc Mutation<'gc>,
receiver: Value<'gc>,
args: Vec<Value<'gc>>,
)
| 189 | |
| 190 | // Return zero-based index of the first item with value equal to x |
| 191 | fn 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 |
| 239 | fn slice<'gc>( |
nothing calls this directly
no test coverage detected