luat_lib_easylvgl_table.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. @module easylvgl.table
  3. @summary EasyLVGL Table 组件
  4. @version 0.1.0
  5. @date 2025.12.26
  6. @tag LUAT_USE_EASYLVGL
  7. */
  8. #include "luat_base.h"
  9. #include "lua.h"
  10. #include "lauxlib.h"
  11. #include "../inc/luat_easylvgl.h"
  12. #include "../inc/luat_easylvgl_component.h"
  13. #include "../inc/luat_easylvgl_binding.h"
  14. #define EASYLVGL_TABLE_MT "easylvgl.table"
  15. static int l_easylvgl_table(lua_State *L) {
  16. easylvgl_ctx_t *ctx = NULL;
  17. lua_getfield(L, LUA_REGISTRYINDEX, "easylvgl_ctx");
  18. if (lua_type(L, -1) == LUA_TLIGHTUSERDATA) {
  19. ctx = (easylvgl_ctx_t *)lua_touserdata(L, -1);
  20. }
  21. lua_pop(L, 1);
  22. if (ctx == NULL) {
  23. luaL_error(L, "easylvgl not initialized, call easylvgl.init() first");
  24. return 0;
  25. }
  26. luaL_checktype(L, 1, LUA_TTABLE);
  27. lv_obj_t *table = easylvgl_table_create_from_config(L, 1);
  28. if (table == NULL) {
  29. lua_pushnil(L);
  30. return 1;
  31. }
  32. easylvgl_push_component_userdata(L, table, EASYLVGL_TABLE_MT);
  33. return 1;
  34. }
  35. static int l_table_set_cell_text(lua_State *L) {
  36. lv_obj_t *table = easylvgl_check_component(L, 1, EASYLVGL_TABLE_MT);
  37. int row = luaL_checkinteger(L, 2);
  38. int col = luaL_checkinteger(L, 3);
  39. const char *text = luaL_optstring(L, 4, "");
  40. easylvgl_table_set_cell_text(table, row, col, text);
  41. return 0;
  42. }
  43. static int l_table_set_col_width(lua_State *L) {
  44. lv_obj_t *table = easylvgl_check_component(L, 1, EASYLVGL_TABLE_MT);
  45. int col = luaL_checkinteger(L, 2);
  46. int width = luaL_checkinteger(L, 3);
  47. easylvgl_table_set_col_width(table, col, width);
  48. return 0;
  49. }
  50. static int l_table_gc(lua_State *L) {
  51. easylvgl_component_ud_t *ud = (easylvgl_component_ud_t *)luaL_checkudata(L, 1, EASYLVGL_TABLE_MT);
  52. if (ud != NULL && ud->obj != NULL) {
  53. easylvgl_component_meta_t *meta = easylvgl_component_meta_get(ud->obj);
  54. if (meta != NULL) {
  55. easylvgl_component_meta_free(meta);
  56. }
  57. lv_obj_delete(ud->obj);
  58. ud->obj = NULL;
  59. }
  60. return 0;
  61. }
  62. void easylvgl_register_table_meta(lua_State *L) {
  63. luaL_newmetatable(L, EASYLVGL_TABLE_MT);
  64. lua_pushcfunction(L, l_table_gc);
  65. lua_setfield(L, -2, "__gc");
  66. static const luaL_Reg methods[] = {
  67. {"set_cell_text", l_table_set_cell_text},
  68. {"set_col_width", l_table_set_col_width},
  69. {NULL, NULL}
  70. };
  71. luaL_newlib(L, methods);
  72. lua_setfield(L, -2, "__index");
  73. lua_pop(L, 1);
  74. }
  75. int easylvgl_table_create(lua_State *L) {
  76. return l_easylvgl_table(L);
  77. }