Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. package main
  2.  
  3. import "core:fmt"
  4. import "core:runtime"
  5. import "core:os"
  6. import "core:mem"
  7. import "core:strings"
  8. import "core:strconv"
  9.  
  10. // Letting a user edit an object via the console!
  11.  
  12. SampleObject :: struct {
  13. name: string,
  14. job_title: string,
  15. birth_year: int,
  16. birth_month: int,
  17. }
  18.  
  19. main :: proc() {
  20. person: SampleObject;
  21. person.name = "hasen";
  22. fmt.printf("address of our object: %d\n", cast(rawptr)(&person));
  23. edit_object(&person);
  24. fmt.println("object now is:", person);
  25. }
  26.  
  27. edit_object :: proc(obj: any) {
  28. fmt.println("Editing object:", obj);
  29. // expect a pointer to a struct, or the struct info to be in there somewhere!
  30. ptr : rawptr = obj.data;
  31. info := type_info_of(obj.id);
  32. struct_info: runtime.Type_Info_Struct;
  33.  
  34. findloop: for {
  35. // fmt.println("type_info:", info.variant);
  36. switch v in info.variant {
  37. case runtime.Type_Info_Pointer:
  38. info = v.elem;
  39. ptr = (cast(^rawptr)ptr)^; // ptr was a pointer to a pointer; go inside!
  40. case runtime.Type_Info_Named:
  41. info = v.base;
  42. case runtime.Type_Info_Struct:
  43. struct_info = v;
  44. break findloop;
  45. case:
  46. fmt.println("unknown variant!", v);
  47. return;
  48. }
  49. }
  50. fmt.printf("edit_object :: pointer is: %d\n", ptr);
  51.  
  52. input := make([]byte, 20);
  53. for name, index in struct_info.names {
  54. type := struct_info.types[index];
  55. offset := struct_info.offsets[index];
  56. fieldPtr := rawptr(uintptr(ptr) + offset);
  57. fieldValue := any{fieldPtr, type.id};
  58. fmt.printf("%s> ", name);
  59. count, err := os.read(context.stdin, input);
  60. if err == 0 && count > 1 {
  61. userInput := string(input[:count-1]);
  62. dynamically_assign(fieldValue, userInput);
  63. }
  64. fmt.println("object now is:", obj);
  65. }
  66. }
  67.  
  68. dynamically_assign :: proc(obj: any, userInput: string) {
  69. ptr := obj.data;
  70. switch it in obj {
  71. case int: (cast(^int)ptr)^ = strconv.parse_int(userInput);
  72. case uint: (cast(^uint)ptr)^ = strconv.parse_uint(userInput);
  73. case i64: (cast(^i64)ptr)^ = strconv.parse_i64(userInput);
  74. case u64: (cast(^u64)ptr)^ = strconv.parse_u64(userInput);
  75. case string: (cast(^string)ptr)^ = strings.clone(userInput);
  76. case: fmt.println("we don't know how to assigned to", obj);
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement